Skip to content

Instantly share code, notes, and snippets.

@ashish173
Created December 8, 2016 21:29
Show Gist options
  • Save ashish173/45180e959d112b7c8ee8980dd25afdd9 to your computer and use it in GitHub Desktop.
Save ashish173/45180e959d112b7c8ee8980dd25afdd9 to your computer and use it in GitHub Desktop.
SwitchMap operator
//emit immediately, then every 5s
const source = Rx.Observable.timer(0, 5000);
//switch to new inner observable when source emits, emit items that are emitted
const example = source.switchMap(() => Rx.Observable.interval(500));
//output: 0,1,2,3,4,5,6,7,8,9...0,1,2,3,4,5,6,7,8
const subscribe = example.subscribe(val => console.log(val));
//emit every click
const sourceTwo = Rx.Observable.fromEvent(document, 'click');
//if another click comes within 3s, message will not be emitted
const exampleTwo = sourceTwo.switchMap(val => Rx.Observable.interval(3000).mapTo('Hello, I made it!'));
//(click)...3s...'Hello I made it!'...(click)...2s(click)...
const subscribeTwo = exampleTwo.subscribe(val => console.log(val));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment