转换IEnumerable <task <t>&gt;到IObservable <t> </t> </task <t>

时间:2013-06-11 18:22:18

标签: c# .net task-parallel-library system.reactive

我正在尝试使用Reactive Extensions(Rx)在任务完成时缓冲它们的枚举。有谁知道是否有一个干净的内置方式这样做? ToObservable扩展方法只会生成IObservable<Task<T>>,这不是我想要的,我想要IObservable<T>,然后我可以使用Buffer

受挫的例子:

//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
    });
}

1 个答案:

答案 0 :(得分:7)

您可以使用Task可以使用another overload of ToObservable()futureInts.Select(t => t.ToObservable()) .Merge() .Buffer(15) .Subscribe(ints => Console.WriteLine(ints.Count)); 转换为可观察的事实。

当您拥有(单项)可观察对象的集合时,您可以使用Merge()创建一个包含完成项目的可观察对象。

因此,您的代码可能如下所示:

{{1}}