share

signature: share(): Observable

Share source among multiple subscribers.


:bulb: share is like multicast with a Subject and refCount!


share - 图2

Examples

Example 1: Multiple subscribers sharing source

( jsBin |
jsFiddle )

  1. import { timer } from 'rxjs/observable/timer';
  2. import { tap, mapTo, share } 'rxjs/operators';
  3. //emit value in 1s
  4. const source = timer(1000);
  5. //log side effect, emit result
  6. const example = source.pipe(
  7. tap(() => console.log('***SIDE EFFECT***')),
  8. mapTo('***RESULT***')
  9. );
  10. /*
  11. ***NOT SHARED, SIDE EFFECT WILL BE EXECUTED TWICE***
  12. output:
  13. "***SIDE EFFECT***"
  14. "***RESULT***"
  15. "***SIDE EFFECT***"
  16. "***RESULT***"
  17. */
  18. const subscribe = example.subscribe(val => console.log(val));
  19. const subscribeTwo = example.subscribe(val => console.log(val));
  20. //share observable among subscribers
  21. const sharedExample = example.pipe(share());
  22. /*
  23. ***SHARED, SIDE EFFECT EXECUTED ONCE***
  24. output:
  25. "***SIDE EFFECT***"
  26. "***RESULT***"
  27. "***RESULT***"
  28. */
  29. const subscribeThree = sharedExample.subscribe(val => console.log(val));
  30. const subscribeFour = sharedExample.subscribe(val => console.log(val));

Additional Resources


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