defer
Creates an Observable that, on subscribe, calls an Observable factory to make an Observable for each new Observer.
Creates the Observable lazily, that is, only when it is subscribed.
defer
allows you to create an Observable only when the Observer
subscribes. It waits until an Observer subscribes to it, calls the given
factory function to get an Observable -- where a factory function typically
generates a new Observable -- and subscribes the Observer to this Observable.
In case the factory function returns a falsy value, then EMPTY is used as
Observable instead. Last but not least, an exception during the factory
function call is transferred to the Observer by calling error
.
Example
Subscribe to either an Observable of clicks or an Observable of interval, at random
import { defer, fromEvent, interval } from 'rxjs';
const clicksOrInterval = defer(() => {
return Math.random() > 0.5
? fromEvent(document, 'click')
: interval(1000);
});
clicksOrInterval.subscribe(x => console.log(x));
// Results in the following behavior:
// If the result of Math.random() is greater than 0.5 it will listen
// for clicks anywhere on the "document"; when document is clicked it
// will log a MouseEvent object to the console. If the result is less
// than 0.5 it will emit ascending numbers, one every second(1000ms).