Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs 6: Get ConnectableObservable from Observable

Angular 6 requires an update to RxJs 6 and with that RxJs update the Observable.publish() function is gone. I found a publish operator in RxJs/operators but I'm having trouble figuring out how to use it.

How could this RxJs 5 code be rewritten to work with RxJs 6?

const myConnectableObservable = this.getObservable().publish()

like image 498
Kevin Kalitowski Avatar asked May 16 '18 13:05

Kevin Kalitowski


People also ask

What connectable Observable?

A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can wait for all intended observers to subscribe to the Observable before the Observable begins emitting items.

What is take in Observable?

take returns an Observable that emits only the first count values emitted by the source Observable. If the source emits fewer than count values then all of its values are emitted. After that, it completes, regardless if the source completes.

What does pipe to Observable?

The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.

What is publish in RxJS?

RxJS publish() operator is a multicasting operator that returns a ConnectableObservable, a variety of Observable that waits until its connect method is called before it begins emitting items to those Observers that have subscribed to it.


1 Answers

import { ConnectableObservable } from "rxjs"
import { publish } from "rxjs/operators";

const myConnectableObservable: ConnectableObservable<MyClass> = myService.getObservable().pipe(publish()) as ConnectableObservable<MyClass>;

Special thanks to @cartant

like image 191
Kevin Kalitowski Avatar answered Sep 20 '22 02:09

Kevin Kalitowski