multicast.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { connectableObservableDescriptor } from '../observable/ConnectableObservable';
  2. /* tslint:enable:max-line-length */
  3. /**
  4. * Returns an Observable that emits the results of invoking a specified selector on items
  5. * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
  6. *
  7. * <img src="./img/multicast.png" width="100%">
  8. *
  9. * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
  10. * which the source sequence's elements will be multicast to the selector function
  11. * or Subject to push source elements into.
  12. * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
  13. * as many times as needed, without causing multiple subscriptions to the source stream.
  14. * Subscribers to the given source will receive all notifications of the source from the
  15. * time of the subscription forward.
  16. * @return {Observable} An Observable that emits the results of invoking the selector
  17. * on the items emitted by a `ConnectableObservable` that shares a single subscription to
  18. * the underlying stream.
  19. * @method multicast
  20. * @owner Observable
  21. */
  22. export function multicast(subjectOrSubjectFactory, selector) {
  23. return function multicastOperatorFunction(source) {
  24. let subjectFactory;
  25. if (typeof subjectOrSubjectFactory === 'function') {
  26. subjectFactory = subjectOrSubjectFactory;
  27. }
  28. else {
  29. subjectFactory = function subjectFactory() {
  30. return subjectOrSubjectFactory;
  31. };
  32. }
  33. if (typeof selector === 'function') {
  34. return source.lift(new MulticastOperator(subjectFactory, selector));
  35. }
  36. const connectable = Object.create(source, connectableObservableDescriptor);
  37. connectable.source = source;
  38. connectable.subjectFactory = subjectFactory;
  39. return connectable;
  40. };
  41. }
  42. export class MulticastOperator {
  43. constructor(subjectFactory, selector) {
  44. this.subjectFactory = subjectFactory;
  45. this.selector = selector;
  46. }
  47. call(subscriber, source) {
  48. const { selector } = this;
  49. const subject = this.subjectFactory();
  50. const subscription = selector(subject).subscribe(subscriber);
  51. subscription.add(source.subscribe(subject));
  52. return subscription;
  53. }
  54. }
  55. //# sourceMappingURL=multicast.js.map