This is how I thought things through
- The Observable itself would be of a new object type called Subject.
- This Subject object should expose the
subscribeshould be called by observers to subscribe to the observable stream of data.
nextshould be called by the Subject owner to push/publish new data whenever available.
- Additionally, I wanted the Subject owner to be able to know whenever no observers were interested in its data. This would enable the Subject owner to decide if he still wanted to get the data or not.
- Also, the Subject owner should be able to know whenever at least one observer started being interested in its data. This would give the Subject owner more control on its data flow and any related operations.
- Now back to the observer. He should be able to unsubscribe from the Subject at any time.
- This leads us to a new object type called Subscription.
- This Subscription object should expose an
unsubscribeshould be called by the observer whenever he wants to stop listening to the data stream coming from the Subject.
Following these rules, I came up with the following implementation.
Note that Subscription just notifies the Subject when the
unsubscribe function is called.
Somewhere in the Subject Owner
Somewhere in the Observer
That’s it, everything worked like a charm and I was proud of what I achieved.
Hope you found reading this story as interesting as I found writing it.
This article was originally published here.