| 1 |
import { Observable } from '../Observable'; |
| 2 |
import { ObservedValueOf, ObservableInput } from '../types'; |
| 3 |
import { innerFrom } from './innerFrom'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Creates an Observable that, on subscribe, calls an Observable factory to |
| 7 |
* make an Observable for each new Observer. |
| 8 |
* |
| 9 |
* <span class="informal">Creates the Observable lazily, that is, only when it |
| 10 |
* is subscribed. |
| 11 |
* </span> |
| 12 |
* |
| 13 |
*  |
| 14 |
* |
| 15 |
* `defer` allows you to create an Observable only when the Observer |
| 16 |
* subscribes. It waits until an Observer subscribes to it, calls the given |
| 17 |
* factory function to get an Observable -- where a factory function typically |
| 18 |
* generates a new Observable -- and subscribes the Observer to this Observable. |
| 19 |
* In case the factory function returns a falsy value, then EMPTY is used as |
| 20 |
* Observable instead. Last but not least, an exception during the factory |
| 21 |
* function call is transferred to the Observer by calling `error`. |
| 22 |
* |
| 23 |
* ## Example |
| 24 |
* |
| 25 |
* Subscribe to either an Observable of clicks or an Observable of interval, at random |
| 26 |
* |
| 27 |
* ```ts |
| 28 |
* import { defer, fromEvent, interval } from 'rxjs'; |
| 29 |
* |
| 30 |
* const clicksOrInterval = defer(() => { |
| 31 |
* return Math.random() > 0.5 |
| 32 |
* ? fromEvent(document, 'click') |
| 33 |
* : interval(1000); |
| 34 |
* }); |
| 35 |
* clicksOrInterval.subscribe(x => console.log(x)); |
| 36 |
* |
| 37 |
* // Results in the following behavior: |
| 38 |
* // If the result of Math.random() is greater than 0.5 it will listen |
| 39 |
* // for clicks anywhere on the "document"; when document is clicked it |
| 40 |
* // will log a MouseEvent object to the console. If the result is less |
| 41 |
* // than 0.5 it will emit ascending numbers, one every second(1000ms). |
| 42 |
* ``` |
| 43 |
* |
| 44 |
* @see {@link Observable} |
| 45 |
* |
| 46 |
* @param observableFactory The Observable factory function to invoke for each |
| 47 |
* Observer that subscribes to the output Observable. May also return any |
| 48 |
* `ObservableInput`, which will be converted on the fly to an Observable. |
| 49 |
* @return An Observable whose Observers' subscriptions trigger an invocation of the |
| 50 |
* given Observable factory function. |
| 51 |
*/ |
| 52 |
export function defer<R extends ObservableInput<any>>(observableFactory: () => R): Observable<ObservedValueOf<R>> { |
| 53 |
return new Observable<ObservedValueOf<R>>((subscriber) => { |
| 54 |
innerFrom(observableFactory()).subscribe(subscriber); |
| 55 |
}); |
| 56 |
} |