This is an academic exercise, I’m new to Reactive Extensions and trying to get my head around the technology. I set myself a goal of making an IObservable that returns successive digits of Pi (I happen to be really interested in Pi right at the moment for unrelated reasons). Reactive Extensions contains operators for making observables, the guidance they give is that you should “almost never need to create your own IObsevable”. But I can’t see how I can do this with the ready-made operators and methods. Let me elucidate a bit more.
I was planning to use an algorithm that would involve the expansion of a Taylor series for Arctan. To get the next digit of Pi, I’d expand a few more terms in the series.
So I need the series expansion going on asynchronously, occasionally throwing out the next computed digit to the IObserver. I obviosly don’t want to restart the computation from scratch for each new digit.
Is there a way to implement this behaviour using RX’s built-in operators, or am I going to have to code an IObservable from scratch? What strategy suggests itself?
Simplest way is to create an
Enumerableand then convert it:Usage (for a cold observable, that is every new ‘subscription’ starts creating Pi from scratch):
If you want to make it
hot(everyone shares the same underlying calculation), you can just do this:Which will start the calculation after the first subscriber, and stop it when they all disconnect. Here’s a simple test:
Which should show
hot1printing only for a little while, thenhot2joining in after a short wait but printing the same numbers. If this was done withcold, the two subscriptions would each start from 0.