Is there a way to subscribe an observer as async

前端 未结 3 532
离开以前
离开以前 2021-01-07 00:18

Given a synchronous observer, is there a way to do this:

observable.SubscribeAsync(observer);

And have all methods on the observer

相关标签:
3条回答
  • 2021-01-07 00:22

    If by having the methods on the observer called asynchronously, you mean that you want a situation where a new notification can be published without waiting for handling of the previous notification to complete, then this is something you will have to do yourself. This breaks the contract of Rx, because if you can have multiple notifications in flight at the same time, you can no longer guarantee that notifications are processed in order. I think there are also other concerns with this approach - it's something you'll want to be careful about.

    On the other hand, if you simply want to handle notifications on a different thread from the one that created the notifications, then ObserveOn and SubscribeOn are what you want to look into.

    0 讨论(0)
  • 2021-01-07 00:42

    You might want to look into ObserveOn and SubscribeOn (more information and even more information).

    0 讨论(0)
  • 2021-01-07 00:42

    If you need to call an async method when the stream spits out a new value, the most common solution you will find is to use SelectMany. The problem is that this doesn't wait for the method to finish, causing any tasks created by SelectMany to run in parallel.

    Here's what you need if you want to block the stream while waiting for the async function to finish:

    Observable.Interval(TimeSpan.FromSeconds(1))
              .Select(l => Observable.FromAsync(asyncMethod))
              .Concat()
              .Subscribe();
    

    Or:

    Observable.Interval(TimeSpan.FromSeconds(1))
              .Select(_ => Observable.Defer(() => asyncMethod().ToObservable()))
              .Concat()
              .Subscribe();
    
    0 讨论(0)
提交回复
热议问题