I wrote previously about how you can set up multiple observable sequences and subscribe to them with multiple observers and create a many-to-many relationship between them.
Whilst this is a very flexible model with a clear separation of responsibilities, often it requires more work to set up and is more than what you need for the task at hand. For instance, if you’re receiving a steady stream of inputs and want to log the arrival of new inputs as well as performing some aggregation on them, you don’t necessarily have to create two subscribers for the input but instead make use of the Rx.Observable.Do function.
Like the Rx.Observable.Subscribe function, the Do function can take a subscriber, or two up to three function objects to handle the onNext, onError and onCompleted events, in that order. Unlike the Rx.Observable.Select function, it doesn’t have a return value and therefore won’t allow you to transform the input stream, it’s intended purely for causing side effects.
I’ve put together a quick demo (see below) to illustrate the use of the Do function in conjunction with other common RxJS functions such as Select and Where. For this demo we just need two <span> elements, one to show the running total, the other to show a log message every time a new value is received:
Couple of things to note here:
- line 13 – this is a deliberate attempt to give the observable sequence a random chance of excepting to invoke the onError handler specified in the Do function on line 30
- line 28 – the Do function updates the HTML content in the log <span> element every time it receives a new value
- line 32 – show a different log message when we have exhausted the observable sequence
- line 34 – apply a filter on the observable sequence for all subsequent functions
- line 36 – only odd numbers are fed to this handler
If you are lucky enough (or unlucky enough depending on which scenario you’re trying to test) just refresh the page and try again and hopefully you have better luck the second time around!