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

Changing Behavior with MapTo

Changing Behavior with MapTo

2:32
You often need streams to trigger different behaviors on the data based on which streams triggers. This lessons shows how to use `mapTo` to pass functions into the `scan` operator and have completed control over you data.
Watch this lesson now
Avatar
egghead.io

You often need streams to trigger different behaviors on the data based on which streams triggers. This lessons shows how to use mapTo to pass functions into the scan operator and have completed control over you data.

Avatar
Sam De Boni

I made the following minor changes when working with RxJS 4.0.6:
1. use flatMapLatest in place of switchMapTo
2. use map in place of mapTo
3. assign a function to inc that returns the increment function since map evaluates its argument

const Observable = Rx.Observable;

const startButton = document.querySelector('#start');
const stopButton = document.querySelector('#stop');

const start$ = Observable.fromEvent(startButton, 'click');
const interval$ = Observable.interval(1000);
const stop$ = Observable.fromEvent(stopButton, 'click');

const intervalThatStops$ = interval$
.takeUntil(stop$);

const data = {count:0};
const inc = ()=>(acc)=>({count:acc.count+1});
const reset = (acc)=> data;

start$
.flatMapLatest(intervalThatStops$)
.map(inc)
.startWith(data)
.scan((acc,curr)=> {
return curr(acc);
})
.subscribe((x)=>console.log(x));

Avatar
nader dabit

Thanks for putting this up here, great to know!

In reply to Sam De Boni
Avatar
nader dabit

@Sam, flatMapLatest is giving me an error, "start$.flatMapLatest is not a function", on version "5.0.0-beta.6"

In reply to Sam De Boni
Avatar
Noah Rawlins

with rxjs 5.0.0 beta 7 I had to do this to get his behavior. Note the type on the mapTo. This makes sure it doesn't complain about trying to start an Observable that now emits functions with a plain object in startWith()

start$
  .switchMapTo(intervalThatStops$)
  .mapTo<any>(inc)
  .startWith(data)
  .scan((acc, curr) => curr(acc) )
  .subscribe((x) => console.log(x));
In reply to nader dabit
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?