[6a3a178] | 1 | import { Observable } from '../Observable';
|
---|
| 2 | import { ObservedValueOf, ObservableInput } from '../types';
|
---|
| 3 | /**
|
---|
| 4 | * Creates an Observable that, on subscribe, calls an Observable factory to
|
---|
| 5 | * make an Observable for each new Observer.
|
---|
| 6 | *
|
---|
| 7 | * <span class="informal">Creates the Observable lazily, that is, only when it
|
---|
| 8 | * is subscribed.
|
---|
| 9 | * </span>
|
---|
| 10 | *
|
---|
| 11 | * ![](defer.png)
|
---|
| 12 | *
|
---|
| 13 | * `defer` allows you to create the Observable only when the Observer
|
---|
| 14 | * subscribes, and create a fresh Observable for each Observer. It waits until
|
---|
| 15 | * an Observer subscribes to it, and then it generates an Observable,
|
---|
| 16 | * typically with an Observable factory function. It does this afresh for each
|
---|
| 17 | * subscriber, so although each subscriber may think it is subscribing to the
|
---|
| 18 | * same Observable, in fact each subscriber gets its own individual
|
---|
| 19 | * Observable.
|
---|
| 20 | *
|
---|
| 21 | * ## Example
|
---|
| 22 | * ### Subscribe to either an Observable of clicks or an Observable of interval, at random
|
---|
| 23 | * ```ts
|
---|
| 24 | * import { defer, fromEvent, interval } from 'rxjs';
|
---|
| 25 | *
|
---|
| 26 | * const clicksOrInterval = defer(function () {
|
---|
| 27 | * return Math.random() > 0.5
|
---|
| 28 | * ? fromEvent(document, 'click')
|
---|
| 29 | * : interval(1000);
|
---|
| 30 | * });
|
---|
| 31 | * clicksOrInterval.subscribe(x => console.log(x));
|
---|
| 32 | *
|
---|
| 33 | * // Results in the following behavior:
|
---|
| 34 | * // If the result of Math.random() is greater than 0.5 it will listen
|
---|
| 35 | * // for clicks anywhere on the "document"; when document is clicked it
|
---|
| 36 | * // will log a MouseEvent object to the console. If the result is less
|
---|
| 37 | * // than 0.5 it will emit ascending numbers, one every second(1000ms).
|
---|
| 38 | * ```
|
---|
| 39 | *
|
---|
| 40 | * @see {@link Observable}
|
---|
| 41 | *
|
---|
| 42 | * @param {function(): SubscribableOrPromise} observableFactory The Observable
|
---|
| 43 | * factory function to invoke for each Observer that subscribes to the output
|
---|
| 44 | * Observable. May also return a Promise, which will be converted on the fly
|
---|
| 45 | * to an Observable.
|
---|
| 46 | * @return {Observable} An Observable whose Observers' subscriptions trigger
|
---|
| 47 | * an invocation of the given Observable factory function.
|
---|
| 48 | * @static true
|
---|
| 49 | * @name defer
|
---|
| 50 | * @owner Observable
|
---|
| 51 | */
|
---|
| 52 | export declare function defer<R extends ObservableInput<any> | void>(observableFactory: () => R): Observable<ObservedValueOf<R>>;
|
---|