Rafael Munitić
Rafael Munitić

Reputation: 927

How to get IObservable<T>.ToTask functionality in silverlight

How can I achieve the behavior you get with IObservable ToTask method in Silverlight where the TPL is not provided ? I want exceptions to get promoted up results as IEnumerable and be able to block and wait for Observable to complete.

Here is an example of what I'm doing with ToTask :

int collectionSize = 200;
service.Collection.CreateSampleCollection(size: collectionSize).Wait();
var query = (QuerySource)service.Collection.CollectionTestModel.All();
var queryTask = query.ToTask();
query.Fetch();
var entities = queryTask.Result;
CollectionAssert.AreEquivalent(entities.Select(e => (int)(long)e["Number"]), Enumerable.Range(0, collectionSize));
service.Collection.DeleteTestCollection().Wait();

So what would be a simple way to translate this code in to other RX extensions ? Using Run I have to add onNext and onError(?) and I have to aggregate the results in onNext. Is there a simpler way to do this ?

Upvotes: 0

Views: 320

Answers (2)

Ana Betts
Ana Betts

Reputation: 74654

And if you don't have the latest build of Rx, ToList is easy enough to write anyways:

public static List<T> ToList<T>(this IObservable<T> This)
{
    return This.Aggregate(new List<T>(), (acc, x) => {
        acc.Add(x);
        return acc;
    }).First();
}

Upvotes: 1

Richard Szalay
Richard Szalay

Reputation: 84744

You can use First() to block until there is a value available (likewise, Last also blocks).

If you need all the values, you can download the latest build of Rx and use .ToArray().First().

Upvotes: 2

Related Questions