Given a synchronous observer, is there a way to do this:
observable.SubscribeAsync(observer);
And have all methods on the observer
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.
You might want to look into ObserveOn
and SubscribeOn
(more information and even more information).
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();