Connect Operator
Connecting and multicasting Observables
The connect() operator enables us to connect and multicast multiple Observables.
Example
Let's look at an example of using the connect() operator to create a new multicasted Observable:
import { interval } from "rxjs";
import { connect, map, tap } from "rxjs/operators";
const source = interval(1000).pipe(
tap((value) => console.log(`source: ${value}`))
);
source
.pipe(connect((multicasted) => multicasted.pipe(map((value) => value * 10))))
.subscribe(console.log);
Let's break this down:
- First, we create a
sourceObservable using theinterval()function that will emit a next notification every 1000 ms. - Within the
sourceObservable we'll use thetap()operator to log the next notification value from thesourceObservable. - Next, we'll use the
connect()operator to create a multicasted Observable. - We provide the
selectorfunction to theconnect()operator, which receives the multicasted Observable that has not yet been connected. - We return a new
multicastedObservable where wemap()thevalueby multiplying the value by 10. - Finally, we
subscribe()to the connected Observable. - It's important to note that
selectorfunction is only invoked when we subscribe to thesourceObservable.