简体   繁体   English

转换IEnumerable <Task<T> &gt;到IObservable <T>

[英]Convert IEnumerable<Task<T>> to IObservable<T>

I'm trying to use the Reactive Extensions (Rx) to buffer an enumeration of Tasks as they complete. 我正在尝试使用Reactive Extensions(Rx)在任务完成时缓冲它们的枚举。 Does anyone know if there is a clean built-in way of doing this? 有谁知道是否有一个干净的内置方式这样做? The ToObservable extension method will just make an IObservable<Task<T>> , which is not what I want, I want an IObservable<T> , that I can then use Buffer on. ToObservable扩展方法只会生成一个IObservable<Task<T>> ,这不是我想要的,我想要一个IObservable<T> ,然后我就可以使用Buffer了。

Contrived example: 举例:

//Method designed to be awaitable
public static Task<int> makeInt()
{
     return Task.Run(() => 5);
}

//In practice, however, I don't want to await each individual task
//I want to await chunks of them at a time, which *should* be easy with Observable.Buffer 
public static void Main() 
{
    //Make a bunch of tasks
    IEnumerable<Task<int>> futureInts = Enumerable.Range(1, 100).Select(t => makeInt());

    //Is there a built in way to turn this into an Observable that I can then buffer?
    IObservable<int> buffered = futureInts.TasksToObservable().Buffer(15); //????

    buffered.Subscribe(ints => {
        Console.WriteLine(ints.Count()); //Should be 15
    });
}

You can use the fact that Task can be converted to observable using another overload of ToObservable() . 您可以使用以下事实:可以使用ToObservable()另一个重载Task转换为observable。

When you have a collection of (single-item) observables, you can create a single observable that contains the items as they complete using Merge() . 当您拥有(单项)可观察对象的集合时,您可以使用Merge()创建一个包含完成项目的observable。

So, your code could look like this: 所以,你的代码看起来像这样:

futureInts.Select(t => t.ToObservable())
          .Merge()
          .Buffer(15)
          .Subscribe(ints => Console.WriteLine(ints.Count));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM