share
signature: share(): Observable
share(): ObservableShare source among multiple subscribers.
💡 share is like multicast with a Subject and refCount!
Examples
Example 1: Multiple subscribers sharing source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+ import { timer } from 'rxjs'; import { tap, mapTo, share } from 'rxjs/operators'; //emit value in 1s const source = timer(1000); //log side effect, emit result const example = source.pipe( tap(() => console.log('***SIDE EFFECT***')), mapTo('***RESULT***') ); /* ***NOT SHARED, SIDE EFFECT WILL BE EXECUTED TWICE*** output: "***SIDE EFFECT***" "***RESULT***" "***SIDE EFFECT***" "***RESULT***" */ const subscribe = example.subscribe(val => console.log(val)); const subscribeTwo = example.subscribe(val => console.log(val)); //share observable among subscribers const sharedExample = example.pipe(share()); /* ***SHARED, SIDE EFFECT EXECUTED ONCE*** output: "***SIDE EFFECT***" "***RESULT***" "***RESULT***" */ const subscribeThree = sharedExample.subscribe(val => console.log(val)); const subscribeFour = sharedExample.subscribe(val => console.log(val));Related Recipes
Additional Resources
share 📰 - Official docs
Sharing streams with share 🎥 💵 - John Linquist
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/packages/rxjs/src/internal/operators/share.ts
Last updated