Learn RxJS
Search…
defer

signature: defer(observableFactory: function(): SubscribableOrPromise): Observable

Create an observable with given subscription function.

πŸ’‘ defer is used as part of the iif operator!
​​
​
​

Examples

Example 1: Defer to get current date/time at the time of subscription
1
// RxJS v6+
2
import { defer, of, timer, merge } from 'rxjs';
3
import { switchMap } from 'rxjs/operators';
4
​
5
const s1 = of(new Date()); //will capture current date time
6
const s2 = defer(() => of(new Date())); //will capture date time at the moment of subscription
7
​
8
console.log(new Date());
9
​
10
timer(2000)
11
.pipe(switchMap(_ => merge(s1, s2)))
12
.subscribe(console.log);
13
​
14
/*
15
OUTPUT =>
16
2019-02-10T12:38:30.000Z (currrent date/time from first console log)
17
2019-02-10T12:38:30.000Z (date/time in s1 console log, captured date/time at the moment of observable creation)
18
2019-02-10T12:38:32.000Z (date/time in s2 console log, captured date/time at the moment of subscription)
19
*/
20
​
21
/*//NOTE: 'traditional' js equivalent of timer code above is:
22
setTimeout(() => {
23
s1.subscribe(console.log);
24
s2.subscribe(console.log);
25
}, 2000);
26
*/
Copied!

Additional Resources

  • ​defer πŸ“° - Official docs
Last modified 1yr ago