开发者

Reactive extension - Return same observable or create new?

I am trying to design a service layer abstraction with Rx. I have wrapped up all webservice calls using FromAsyncPattern. I will have multiple ViewModels subscribing to these observables, some can have multiple subscriptions.

  • Shoud I create readonly IObservable<T> properties in my ServiceProxy class (singleton)开发者_JS百科 and construct once in the constructor or should I create new observables every time in service methods and return them ?

  • Does it matter ?


Does it matter ?

In this case, no. This is the difference between a cold observable (like what Create returns) and a hot observable. FromAsyncPattern returns an AsyncSubject, which means that it will "Replay" the result to any subscribers (so, it's cold, but not in exactly the same way, more like 'chilly').

Create, on the other hand, will end up rerunning the code for every subscriber (just like if you had a L2S query, running Foreach on it would issue another database call). Sometimes this is what you want, sometimes it isn't.

To make a Cold observable into a Hot observable, add this to the end:

.Multicast(new Subject<TTheType>()).RefCount();

And if you want to take a hot observable (like Observable.Start) and make it cold, use Defer:

var coldObs = Observable.Defer(() => 
    Observable.Start(() => doSomethingAndReturnAValue()));

This means, that every time someone Subscribes to coldObs, doSomethingAndReturnAValue gets called.


You cannot create IObservalble<T> properties to represent IObservable created from using FromAsyncPattern, as this method returns a function which when called with proper values will return a IObservable<T> (where T is the return type of the original underlying synchronous method). So your Rx abstraction layer will have methods which take the actual parameters as original service layer methods but instead of T returns IObservable<T>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜