Is there a way to subscribe an observer as async

前端 未结 3 534
离开以前
离开以前 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: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();
    

提交回复
热议问题