publish

signature: publish() : ConnectableObservable

Share source and make hot by calling connect.

publish - 图1

Examples

Example 1: Connect observable after subscribers

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/of';
  2. import { publish, tap } 'rxjs/operators';
  3. //emit value every 1 second
  4. const source = interval(1000);
  5. const example = source.pipe(
  6. //side effects will be executed once
  7. tap(_ => console.log('Do Something!')),
  8. //do nothing until connect() is called
  9. publish()
  10. );
  11. /*
  12. source will not emit values until connect() is called
  13. output: (after 5s)
  14. "Do Something!"
  15. "Subscriber One: 0"
  16. "Subscriber Two: 0"
  17. "Do Something!"
  18. "Subscriber One: 1"
  19. "Subscriber Two: 1"
  20. */
  21. const subscribe = example.subscribe(val =>
  22. console.log(`Subscriber One: ${val}`)
  23. );
  24. const subscribeTwo = example.subscribe(val =>
  25. console.log(`Subscriber Two: ${val}`)
  26. );
  27. //call connect after 5 seconds, causing source to begin emitting items
  28. setTimeout(() => {
  29. example.connect();
  30. }, 5000);

Additional Resources

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