Toggle A Stream On And Off With RxJS

InstructorBen Lesh

Share this video with your friends

Send Tweet

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.

Mike
~ 9 years ago

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

Ben Leshinstructor
~ 9 years ago

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)

Roel Van der Paal
~ 8 years ago

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?

Roel Van der Paal
~ 8 years ago

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.

bradwoods.io
~ 8 years ago

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?

Sam
~ 7 years ago

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

Roy
~ 7 years ago

FYI: since Rx 5, flatMapLatest has been renamed to switchMap. flatMap is now mergeMap though the flatMap alias is still around. See https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md