Rxjs SwitchMap Operator by example


You can get an initial starting JavaScript project configured to work with rajas and typescript.

You don’t have to use typescript you don’t want. You can configure Babel compiler instead and use plain JavaScript.

You can get this project from here:


I’ll start with a simple start button.

cost startButton = document.querySelector('#start');

the start Button element, listen for clicks, and then .subscribe() to handle the clicks.

Observable.fromEvent(startButton, 'click')

I’ll add a function to handle the event and log out the ‘click’ event.

Observable.fromEvent(startButton, 'click')
	.subscribe((event) => console.log('The Event: ', event));

To make this more interesting I’ll set up a timer that runs every second and

gets the count of how many times it’s ticked through that time.

To make this more interesting I’ll set up a timer that runs every second and

gets the count of how many times it’s ticked through that time and combine this with the

click event.

Observable.fromEvent(startButton, 'click')
	.subscribe((event) =>{
			.subscribe((x) => console.log(x));

If you run it you will see it logs out. 0, 1, 2, 3, 4 5 …., as expected but this is wrong and I shouldn’t have done it this way.

Having multiple subscription blocks nested inside of each other is an anti-pattern.

One disadvantage of doing it this way is that I’ll lose the ability to save this stream and reuse it, because the moment I subscribe() what comes out of .subscribe() is a subscription, not an Observable.

Other disadvantage is that I could not pass this around and reuse it in other places.

If you are run the provided code or if you are following along you will see that by clicking multiple times you’ll be getting the wrong behavior of creating a new interval every single time start button is clicked.

What I really intended to do was that when I clicked the start Button, the startButton it switched over to an .interval() Observable. Instead of subscribing  to the click I want to  switch to the interval.

something like this:

Observable.fromEvent(startButton, 'click')
	.switchMap(() => Observable.interval(1000))
	.subscribe((x) => console.log(x));

Now this is working correctly, when I’ll click the start button it switches over to the .interval() and is now logging out each of those ticks.

I’ll try now to refactor this so it can be decouple and can be read easily.

Html code here! Replace this with any non empty text and that's it.

const startClick$ = Observable.fromEvent(startButton, 'click');
const interval$ = Observable.interval(1000);

const startInterval$ = startClick$
	.switchMap((event)=> interval$);

	.subscribe((x)=> console.log(x)); 


Please enter your comment!
Please enter your name here