The publishLast
operator from the rxjs
library is used to multicast the last emitted value of an observable to multiple subscribers. It returns a new observable that shares a single subscription to the source observable, and when the source completes, it emits only the last value to all subscribers.
Here's an example of how to use publishLast
:
index.tsx502 chars19 lines
In the example above, we create an observable source$
that emits three values. We then use the tap
operator to log each value emitted by the source observable. Next, we apply the publishLast
operator to source$
to create a new observable shared$
.
We then subscribe twice to shared$
. When connect
is called on the shared$
observable, it subscribes to source$
and begins emitting values. Since publishLast
buffers the last value emitted from source$
, both subscribers receive the last emitted value, which is 3
.
Note that connect
is used to initiate the subscription to source$
and activate the shared$
observable. Without it, nothing would happen because shared$
would not be connected to the source.
gistlibby LogSnag