Is there a way to subscribe an observer as async

我怕爱的太早我们不能终老 提交于 2019-12-30 07:39:27

问题


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

observable.SubscribeAsync(observer);

And have all methods on the observer called asynchronously or is that something I have to handle when creating the observer?


回答1:


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




回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/18814805/is-there-a-way-to-subscribe-an-observer-as-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!