multicast

signature: multicast(selector: Function): Observable

Share source utilizing the provided Subject.

multicast - 图1

Examples

Example 1: multicast with standard Subject

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/of';
  2. import { Subject } from 'rxjs/Subject';
  3. import { take, tap, multicast } 'rxjs/operators';
  4. //emit every 2 seconds, take 5
  5. const source = interval(2000).pipe(take(5));
  6. const example = source.pipe(
  7. //since we are multicasting below, side effects will be executed once
  8. tap(() => console.log('Side Effect #1')),
  9. mapTo('Result!');
  10. );
  11. //subscribe subject to source upon connect()
  12. const multi = example.pipe(multicast(() => new Subject()));
  13. /*
  14. subscribers will share source
  15. output:
  16. "Side Effect #1"
  17. "Result!"
  18. "Result!"
  19. ...
  20. */
  21. const subscriberOne = multi.subscribe(val => console.log(val));
  22. const subscriberTwo = multi.subscribe(val => console.log(val));
  23. //subscribe subject to source
  24. multi.connect();
Example 2: multicast with ReplaySubject

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/of';
  2. import { take, multicast } 'rxjs/operators';
  3. //emit every 2 seconds, take 5
  4. const source = interval(2000).pipe(take(5));
  5. //example with ReplaySubject
  6. const example = source.pipe(
  7. //since we are multicasting below, side effects will be executed once
  8. tap(_ => console.log('Side Effect #2')),
  9. mapTo('Result Two!')
  10. );
  11. //can use any type of subject
  12. const multi = example.pipe(multicast(() => new Rx.ReplaySubject(5)));
  13. //subscribe subject to source
  14. multi.connect();
  15. setTimeout(() => {
  16. /*
  17. subscriber will receieve all previous values on subscription because
  18. of ReplaySubject
  19. */
  20. const subscriber = multi.subscribe(val => console.group(val));
  21. }, 5000);

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/multicast.ts