The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Toggle A Stream On And Off With RxJS

Toggle A Stream On And Off With RxJS

3:52
This lesson covers how to toggle an observable on and off from another observable by showing how to use a checkbox as a toggle for a stream of data.
Watch this lesson now
Avatar
egghead.io

This lesson covers how to toggle an observable on and off from another observable by showing how to use a checkbox as a toggle for a stream of data.

Avatar
Mike

What would be the difference between using flatMapLatest vs flatMap in this instance?

Avatar
Ben

In truth, in this case? Not much difference. The flatMapLatest conveys that there's only one subscription going on at a time inside of the flatMap though.

However, if you were to have a situation where the "toggler" stream (the stream of checks) could return multiple trues in a row like: Observable.of(true, true, false, true, true), then using flatMapLatest will keep the underlying subscriptions to one, where flatMap will allow multiple subscriptions to occur.

Here's an altered version of the same jsbin: https://jsbin.com/cohufemero/edit?js,output

Other things to note, the source stream in this example is a cold observable. If we were dealing with a "hot" observable, we'd need to identify a strategy to deal with values that arrive while toggled "off". (buffer? drop? etc)

In reply to Mike
Avatar
Roel Van der Paal

This example is restarting the stream every time the checkbox is checked.
Is it possible to stop a stream, and continue where it was stopped, when it is toggled on?

Avatar
Roel Van der Paal

Please ignore previous question, I understand it is against the philosophy of Rx to pause streams.

The functionality I like to have is a stream of ascending numbers, that can be paused. I found that that can be achieved by putting a scan function after the flatMapLatest.

In reply to Roel Van der Paal
Avatar
Brad

how does the source stream know when to stop? Before you flatmap you filter the checkbox's stream to only return results when the checkbox is 'checked', which would mean the checkbox being 'unchecked' is not in the stream?

Avatar
Sam

I was confused by this also, how does the observable get 'past' the filter?

In reply to Brad
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?