How to convert an IEnumerable<Task<T>> to IObservable<T>

你说的曾经没有我的故事 提交于 2019-12-30 17:26:23

问题


Is there a built in way to convert an IEnumerable<Task<T>> to an IObservable<T>. Order doesn't matter, just that I get things, though preferably as they're completed.

If it doesn't exist yet, what might be a good way to accomplish it?


回答1:


I believe this will work

tasks.Select(t => Observable.FromAsync(() => t))
     .Merge();

Each task will send its results to the observable sequence in whatever order they complete. You can subscribe to the sequence and do whatever you want with the results that way.




回答2:


You could do it this way:

var query = tasks.ToObservable().SelectMany(task => task.ToObservable());

Or, alternatively, like this:

var query =
    from t in tasks.ToObservable()
    from i in t.ToObservable()
    select i;



回答3:


I believe what you're looking for may be Observable.Start()

You can then append .Subscribe(callbackMethod) to the end and specify a callback if needed.




回答4:


As of Rx 2.0, there's a slightly easier way:

var query = tasks.ToObservable().Merge();


来源:https://stackoverflow.com/questions/13500456/how-to-convert-an-ienumerabletaskt-to-iobservablet

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