Scipion
Scipion

Reputation: 11888

Rxjs Sharing an observable subscription

I have a function with the following code:

private foo() {
    let obs: Observable<any> = this._http.get<number>('/foo')

    obs.subscribe(x=> {
        console.log("foo : " + x)
    });

     this.blah(obs)
}

private blah(obs: Observable<any>) {
    obs.subscribe(x => {
       console.log("blah : " + x)
    })
}

this code is indeed printing both foo and blah, howerver it also does my http call to /foo twice

I would like it to happen only once. I tried replacing the subscribe by do in the blah function but it doesn't work. What's the issue here ?

Upvotes: 2

Views: 145

Answers (1)

martin
martin

Reputation: 96891

That's correct behavior. You're creating two subscriptions and since the http.get creates a "cold" Observable it makes two HTTP calls.

The easiest way to avoid this is to share the source Observable with the share() operator.

let obs = this._http.get<number>('/foo').share();

You could also create a ConnectableObservable with the publish() operator and connect to the shared source manually.

let obs = this._http.get<number>('/foo').publish();

obs.subscribe(x=> {
    console.log("foo : " + x)
});

this.blah(obs);

obs.connect();

Upvotes: 2

Related Questions