share
연산자(operator) 정의: share(): Observable
Share source among multiple subscribers.
share is like multicast with a Subject and refCount!
Examples
Example 1: Multiple subscribers sharing source
//emit value in 1s
const source = Rx.Observable.timer(1000);
//log side effect, emit result
const example = source
.do(() => 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.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));
Additional Resources
- share - Official docs
- Sharing streams with share - John Linquist
Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/operator/share.ts