publish.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { Observable } from '../Observable';
  2. import { Subject } from '../Subject';
  3. import { multicast } from './multicast';
  4. import { ConnectableObservable } from '../observable/ConnectableObservable';
  5. import { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservableInput, ObservedValueOf } from '../types';
  6. /* tslint:disable:max-line-length */
  7. export function publish<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>>;
  8. export function publish<T, O extends ObservableInput<any>>(selector: (shared: Observable<T>) => O): OperatorFunction<T, ObservedValueOf<O>>;
  9. export function publish<T>(selector: MonoTypeOperatorFunction<T>): MonoTypeOperatorFunction<T>;
  10. /* tslint:enable:max-line-length */
  11. /**
  12. * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
  13. * before it begins emitting items to those Observers that have subscribed to it.
  14. *
  15. * <span class="informal">Makes a cold Observable hot</span>
  16. *
  17. * ![](publish.png)
  18. *
  19. * ## Examples
  20. * Make source$ hot by applying publish operator, then merge each inner observable into a single one
  21. * and subscribe.
  22. * ```ts
  23. * import { of, zip, interval, merge } from "rxjs";
  24. * import { map, publish, tap } from "rxjs/operators";
  25. *
  26. * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9)).pipe(
  27. * map(values => values[1])
  28. * );
  29. *
  30. * source$
  31. * .pipe(
  32. * publish(multicasted$ =>
  33. * merge(
  34. * multicasted$.pipe(tap(x => console.log('Stream 1:', x))),
  35. * multicasted$.pipe(tap(x => console.log('Stream 2:', x))),
  36. * multicasted$.pipe(tap(x => console.log('Stream 3:', x))),
  37. * )
  38. * )
  39. * )
  40. * .subscribe();
  41. *
  42. * // Results every two seconds
  43. * // Stream 1: 1
  44. * // Stream 2: 1
  45. * // Stream 3: 1
  46. * // ...
  47. * // Stream 1: 9
  48. * // Stream 2: 9
  49. * // Stream 3: 9
  50. * ```
  51. *
  52. * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
  53. * as needed, without causing multiple subscriptions to the source sequence.
  54. * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
  55. * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
  56. * @method publish
  57. * @owner Observable
  58. *
  59. *
  60. */
  61. export function publish<T, R>(selector?: OperatorFunction<T, R>): MonoTypeOperatorFunction<T> | OperatorFunction<T, R> {
  62. return selector ?
  63. multicast(() => new Subject<T>(), selector) :
  64. multicast(new Subject<T>());
  65. }