In a previous post, I created a sample app to demonstrate switchMap operator. In this post, I will build on that example and use it to demonstrate takeUntil operator in order to implement the stop functionality of the start interval.

To begin with, create a stop <button> with a label of Stop and create a new query selector for the button.

To stop the interval initialized from the start I will show what I did. I’ll do it the wrong way so I can show what not to do as this is a common mistake I’ve seen.

What I’m doing is saving the subscription interval$.subscribe() returns

And then using it to unsubscribe once the stop button is clicked.

This will work as I said this is wrong it shouldn’t be done this way.

Instead of getting references to subscriptions, we should have streams work together. We want an interval$ that goes until a stopButton interval$ fires.

The correct way of doing this will look something like this:

which reads as : run this interval$ until (.takeUntil() operator) the other observable (Observable.fromEvent(stopButton, ‘click’)) gets clicked.

This will work and will be fine but we can improve its look so it’s easier to read and maintain.

and finally all together will looks like this:

https://github.com/cdcalderon/RxjsTrainingPlayground

LEAVE A REPLY

Please enter your comment!
Please enter your name here