IObservable.Subscribe OnNext action is not blocking in blazor webassembly

150 Views Asked by At

I am using https://github.com/dotnet/reactive I use CombineLatest to combine observableA (emits items by timer) with observableB (insert manually). In OnNext method sometimes i insert new value to observableB In that case new iteration of OnNext starts immediately before current OnNext returns.

 _subscription = _observable.ClientData
        .CombineLatest(_deviceTypeFilterViewModel.Filters)
        .Subscribe(OnNext, OnError);

private void OnNext((IClientDataSlice slice, Filtter filter) sliceWithFilter)
{
   Logger.Log(Slice.Number + " start");
   //... pseudo code:
   _deviceTypeFilterViewModel.Filters.Add(someValue)
   Logger.Log(Slice.Number + " end");
}

Will be executed like:

1 start
2 start
....

Instead of

1 start 
1 finish
2 start
2 finish

When i did the same in blazor server hosted it worked as expected: new OnNext not started untill previous method returns. Is that by design?

1

There are 1 best solutions below

0
Stroniax On

Publishing a value is just like invoking an event delegate. Calling OnNext on your subject (or however you're publishing to ObservableB) is going to synchronously call OnNext in your observer, which means that method will run to completion before your code continues. This can be changed by adding .ObserveOn(ThreadPoolScheduler.Default) to your rx chain. Doing so would cause publishing a value to trigger threadpool work, which will wait for a threadpool thread to become available and run it there. This still won't make your first subscription complete before the second one runs - for that, you may need to look into a primitive locking mechanism or consider calling .Synchronize() in your rx chain (depending on the code you have running). Note that these options could cause a deadlock if you don't properly dispatch your work to the threadpool.