Saturday, April 14, 2012

Subscription snooping in Rx

When debugging using Reactive, I have often had the need to know
  • if subscription took place to the source 
  • if the client was still subscribed
  • the sub was dispose accidentally, if yes, when etc.
These are especially useful to know when one is starting to learn Rx. To achieve this, I created a simple extension method and I further extended it to include various stages of subscriptions and disposals. Following class honors the various stages related to sub:

Subscribing(before subscriptions takes place)
Subscribed(after subscription has happened)
Disposing(before subscription is about to be disposed)
Disposed(Subscription has been disposed)

For each stage, it will accept an Action which will be called by these methods. I abstracted it this way as I plan to extend abilities of snooping into the observable.


Note: I also want to add that you should be able to use Observable.Create to achieve this as well as shown here.

This can then be wrapped into an extension methods like this:

I added few extension methods like OnSubscribing, OnSubscribed, OnDisposing, OnDisposed etc. Typically though one would only be interested before Subscribing and after Disposal of the subscription. Here is the sample code which uses this method:

Here is the output in console. Note that it immediately shows that Take extension method disposes off the subscription:


Actullay I was puzzled that why did the subscription get disposed off as shown above. After further investigation, when I took off SubscribeOn combinator, it behaved differently:

The output here is as follows:


Note that now, the subscription is not being disposed off. These extension methods can throw some light into inner workings of the reactive subscription flow.

Also note that I created another extension method, WhenSubscribedOrDisposed, which lets you specify all four actions together. The advantage is that we are now creating one object vs 4 as before:


Useful Links:
  • Sample code is available here as a gist.
  • Using Observable.Create to do something similar is here.

No comments:

Post a Comment