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);

See example on codesandbox

Let's break this down:

  • First, we create a source Observable using the interval() function that will emit a next notification every 1000 ms.
  • Within the source Observable we'll use the tap() operator to log the next notification value from the source Observable.
  • Next, we'll use the connect() operator to create a multicasted Observable.
  • We provide the selector function to the connect() operator, which receives the multicasted Observable that has not yet been connected.
  • We return a new multicasted Observable where we map() the value 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 the source Observable.