8

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

Kevin Kalitowski
  • 6,829
  • 4
  • 36
  • 52
  • As a temporarily work-around you can use the rxjs-compat module to keep compatibility with version 5. – Christian Benseler May 16 '18 at 13:12
  • 1
    @ChristianBenseler for sure, and thanks. I was trying to be proactive about fixing it now at my leisure instead of being forced to with RxJs 7. Though at that point there should be more resources online. – Kevin Kalitowski May 16 '18 at 13:15
  • Yeah, I'm facing some issues with the migration, too, and trying to don't use the rxjs-compat in order to have less problems when version 7 will be released. – Christian Benseler May 16 '18 at 13:17
  • 2
    `this.getObservable().pipe(publish()) as ConnectableObservable` but, ideally, with an appropriate type instead of the `any`. – cartant May 16 '18 at 13:21
  • See also https://stackoverflow.com/a/50166414/6680611 – cartant May 16 '18 at 13:22
  • See this issue - (and especially my comment) - https://github.com/ReactiveX/rxjs/issues/2972 – Simon_Weaver Jan 14 '19 at 01:53

2 Answers2

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

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

Special thanks to @cartant

Kevin Kalitowski
  • 6,829
  • 4
  • 36
  • 52
  • It seems `Observable` has a `publish` method. I tried to use it directly but got error that `publish` doesn't exist. I had to use `pipe(publish())`. Could you please tell me why directly using `publish` doesn't work? – Manu Chadha Sep 26 '19 at 10:26
0

You can alternatively try this version without casting to the ConnectableObservable type. This way you don't need import and cast. This is needed because according to the documentation pipe() always returns Observable.

import { interval } from 'rxjs';
import { filter, publish } from 'rxjs/operators';

const source = interval(400);

const observable = publish()(source.pipe(
  filter(x => x % 2 === 0),
));

observable.connect();

Originally posted on RxJS GitHub repository as an issue, see link to the issue.

Goga Koreli
  • 2,807
  • 1
  • 12
  • 31