javascript / expert
Snippet
Advanced Observable Multicasting with share()
The share() operator is often used too simply. By configuring the connector and reset policies, you can control exactly how a stream is cached (e.g., using ReplaySubject) and when the underlying producer should be torn down or restarted.
snippet.js
1
2
3
4
5
6
7
8
const shared$ = source$.pipe(share({connector: () => new ReplaySubject(1),resetOnComplete: false,resetOnError: false,resetOnRefCountZero: true}));
angular
Breakdown
1
connector: () => new ReplaySubject(1)
Defines the internal subject used to multicast values, in this case caching the last emitted value.
2
resetOnRefCountZero: true
Ensures the source is unsubscribed when all observers disconnect, saving resources in complex SPAs.