SwitchMap

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

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

You can get this project from here:

https://github.com/cdcalderon/RxjsTrainingPlayground/releases/tag/v1.0.0

I’ll start with a simple start button.

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

I’ll add a function to handle the event and log out the ‘click’ 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.

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:

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here