The publishReplay()
function from the RxJS library creates a ConnectableObservable
that shares a single subscription and multicast emissions to all subscribers. This is useful for cases where you need to perform side-effects only once and share the result of an observable stream to multiple subscribers.
Here is an example of how to use publishReplay()
in JavaScript:
index.tsx288 chars13 lines
In this example, we create an observable obs$
that emits the string 'data'
and performs a side-effect of logging to the console. We use publishReplay()
to make obs$
a ConnectableObservable that shares a single subscription and caches the emitted value for all subscribers. We use refCount()
to automatically connect and disconnect the observable based on the number of subscribers.
When we subscribe to obs$
twice, we see that the side-effect is only performed once and both subscribers receive the same cached value:
index.tsx42 chars5 lines
gistlibby LogSnag