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
source
Observable using theinterval()
function that will emit a next notification every 1000 ms. - Within the
source
Observable we'll use thetap()
operator to log the next notification value from thesource
Observable. - Next, we'll use the
connect()
operator to create a multicasted Observable. - We provide the
selector
function to theconnect()
operator, which receives the multicasted Observable that has not yet been connected. - We return a new
multicasted
Observable where wemap()
thevalue
by multiplying the value by 10. - Finally, we
subscribe()
to the connected Observable. - It's important to note that
selector
function is only invoked when we subscribe to thesource
Observable.