skip to content

defer

 

Create Observable at the time of subscription

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const { rxObserver } = require('api/v0.3');
const { defer, of } = require('rxjs');

// decides later what observable to return
const source$ = defer(()=>{
  if (Date.now() < 3) {
    return of('🐦');
  }

  return of('🦉');
});

// subsctibe at T0
source$.subscribe(rxObserver('Early bird'));

// delayed subscription
setTimeout(()=>{
  source$.subscribe(rxObserver('Night owl'));
}, 5);

0msEarly birdstartcomplete🐦🐦 Night owlstartcomplete🦉🦉

To switch between two Observables see iif function