I am currently lucky enough to be making use of RX at work, and I must say – as with most people who have the chance to use it, I love it.
It is amazing to be able to pass an observable around your application, combine it with other observables, subscribe to the result and have events pumped straight to you when and how you want. You hear the term composable banded about but without seeing it done it’s hard to appreciate.
A recent requirement was for a screen to subscribe to push updates from the server every time a set of data is retrieved. Whenever a new set of data is retrieved, then a new subscription for push updates is setup, at the same time we no longer need to continue receiving the updates from the previous set so we need to ensure that this is torn down.
The RX Switch operator looked like a perfect operator to take care of this – however I wanted to make sure that the old subscription is disposed of so we are not keeping needless connections open.
The behaviour of Switch() is easy to test:
The above code will create two observables, i being 1 then 2 in each case. We are looking to see the first observable is being disposed i.e the one with i being of value 1.
This passes and shows that with the Switch operator, the subscription to the first observable is indeed disposed of when the second observable is created and used as the new subscription. If Switch() is replaced with Merge() for example, then understandably both are kept alive and the test fails.