The Grand User
The Grand User

Reputation: 727

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

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?

Upvotes: 9

Views: 984

Answers (4)

Dave Sexton
Dave Sexton

Reputation: 2652

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

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

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117027

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;

Upvotes: 2

Bryan Anderson
Bryan Anderson

Reputation: 16129

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.

Upvotes: 7

Khan
Khan

Reputation: 18142

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.

Upvotes: 1

Related Questions