Rxjs共享可观察的订阅

时间:2017-11-16 07:20:32

标签: javascript angular typescript rxjs

我有一个带有以下代码的函数:

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

此代码确实同时打印了fooblah,同时它也会对我{http} /foo进行两次调用

我希望它只发生一次。我尝试在blah函数中替换subscribe do,但它不起作用。 这里的问题是什么?

1 个答案:

答案 0 :(得分:2)

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