[RxJS] Share vs ShareReply
https://www.learnrxjs.io/learn-rxjs/operators/multicasting/sharereplay
https://www.learnrxjs.io/learn-rxjs/operators/multicasting/share
Share and ShareReplay, they are mainly the same. Just for ShareReplay, the subscriber subscribe after event emitted can also get value, similar to ReplaySubject.
// simulate url change with subject const routeEnd = new Subject(); // grab url and share with subscribers const lastUrl = routeEnd.pipe( pluck('url'), share() ); // initial subscriber required const initialSubscriber = lastUrl.subscribe(console.log); // nothing // simulate route change routeEnd.next({data: {}, url: 'my-path'}); // nothing logged const lateSubscriber = lastUrl.subscribe(console.log); // my-path
In the code, only lateSubscribe got the value. initialSubscribe didn't get the value.
import { Subject } from 'rxjs/Subject'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { pluck, share, shareReplay, tap } from 'rxjs/operators'; // simulate url change with subject const routeEnd = new Subject<>(); // grab url and share with subscribers const lastUrl = routeEnd.pipe( tap(_ => console.log('executed')), pluck('url'), // defaults to all values so we set it to just keep and replay last one shareReplay(1) ); // requires initial subscription const initialSubscriber = lastUrl.subscribe(console.log); // simulate route change // logged: 'executed', 'my-path' routeEnd.next({data: {}, url: 'my-path'}); // logged: 'my-path' const lateSubscriber = lastUrl.subscribe(console.log);
Both got the value.
Side effect only execute once
import { timer } from "rxjs"; import { tap, mapTo, shareReplay, 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));
If we use share or shareReplay(1)
//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));
Side effect only execute once