50d1f3a4c0d4a88870f58d2ed0bf82d49a7af60ef057248585013254d14c8e0bf1c5f7ed1de540fea2092d7cbe643f5873dda2801f9a0be37ccb1ac6a2af30 2.2 KB

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