Share Operator
Multicasting made easy
The share()
operator makes multicasting easy.
Let's look at an example.
import { Observable, Subject } from "rxjs";
import { share, takeUntil } from "rxjs/operators";
const completeSubject = new Subject<void>();
/* Create a new observable, providing the observer. */
const observable = new Observable<number>((observer) => {
console.log("%cNew subscription created", "background: #222; color: #bada55");
let i = 0;
const interval = setInterval(() => {
observer.next(i++);
}, 1000);
return () => {
clearInterval(interval);
};
}).pipe(takeUntil(completeSubject));
const multicasted = observable.pipe(share());
/* Each subscription receives a copy of Observer. */
multicasted.subscribe((value) => console.log("First subscription", value));
multicasted.subscribe((value) => console.log("Second subscription", value));
/* Complete the observable after 5 seconds. */
setTimeout(() => {
completeSubject.next();
}, 5000);
Let's break this down:
- First, we define
completeSubject
, which we will use to trigger the completion of theobservable
using thetakeUntil()
operator. - We are creating a new
Observable
that emits anumber
value every 1000 milliseconds. - We use the
share()
operator to create a multicasted Observable. - We subscribe multiple times to the connected and multicasted Observable that was created by the
share()
operator. - Finally, after 5000 milliseconds we complete the source Observable.
Note, that with the share()
operator we do not have an opportunity to define the implementation of the multicasted Observable.
Rather, simply put, the share()
operator multicasts the source Observable.