Skip to content

Instantly share code, notes, and snippets.

@kosich
Last active May 24, 2019 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosich/070a57d163cae958473b6ee36e9b0798 to your computer and use it in GitHub Desktop.
Save kosich/070a57d163cae958473b6ee36e9b0798 to your computer and use it in GitHub Desktop.
switchMap subscription
const { rxObserver } = require('api/v0.3');
const { defer, timer, Subject } = require('rxjs');
const { take, switchMap, startWith, endWith, share } = require('rxjs/operators');
// OPEN THE CONSOLE TO SEE SUBSCRIPTION TIMINGS
// defer is called each time it is subscribed to
const source$ = defer(()=>{
console.log('subscribed at ', Date.now());
// will emit an event in 10ms
return timer(10);
})
// UNCOMMENT THIS TO SHARE THE SOURCE
// .pipe(share());
source$.pipe(
take(1),
switchMap(value => source$.pipe(
startWith('>'),
endWith('<')
))
).subscribe(rxObserver('result'));
const { rxObserver } = require('api/v0.3');
const { defer, timer, Subject } = require('rxjs');
const { take, switchMap, startWith, endWith } = require('rxjs/operators');
// create a hot observable
const hotSource$ = new Subject();
timer(10, 10).pipe(take(5)).subscribe(hotSource$);
// display real source emission
hotSource$.subscribe(rxObserver('real result'));
// and wrapped emission
// as you can see, it omits the first value
hotSource$.pipe(
take(1),
switchMap(value => hotSource$.pipe(
// UNCOMMENT THIS LINE TO GET THE FIRST VALUE
// startWith(value),
startWith('>'),
endWith('<')
))
).subscribe(rxObserver('wrapped result'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment