how to use the connectable function from the rxjs library in typescript

To use the connectable function from the rxjs library in TypeScript, you'll need to import it along with other necessary modules:

import { Observable } from 'rxjs/Observable';
import { ConnectableObservable } from 'rxjs/observable/ConnectableObservable';
import { publish } from 'rxjs/operators';
167 chars
4 lines

The above code imports the Observable and ConnectableObservable classes, as well as the publish operator, which is often used together with connectable.

Once you have your observable, you can create a ConnectableObservable using the connectable function:

const source = Observable.create(observer => {
  observer.next('Hello');
  observer.next('World');
});

const connectableSource = source.pipe(publish()) as ConnectableObservable<string>;

connectableSource.subscribe(val => console.log(`Subscriber 1: ${val}`));
connectableSource.subscribe(val => console.log(`Subscriber 2: ${val}`));

connectableSource.connect();
364 chars
12 lines

In the above example, we created a simple Observable that emits two values. We then called the publish operator to convert it to a ConnectableObservable. Finally, we subscribed to the ConnectableObservable, and called connect to start emitting values.

By doing this, both subscribers receive every emitted value, as opposed to each having their own separate subscription and receiving separate emissions. This can be useful in a variety of scenarios where you want to share a single source of emissions across multiple subscribers.

gistlibby LogSnag