Learn RxJS
Search…
share

signature: share(): Observable

Share source among multiple subscribers.

πŸ’‘ share is like multicast with a Subject and refCount!
​​
​
​

Examples

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

Additional Resources

Last modified 1yr ago