有没有办法检查源是否被订阅?

7 javascript typescript rxjs5 angular

正如标题所说,在 Angular 2 中,有没有办法检查源是否已经订阅?因为我必须在使用前检查它

this.subscription.unsubscribe();
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

this.Source = Rx.Observable.timer(startTime, 60000).timeInterval().pluck('interval');

this.Subscription = this.Source
  .subscribe(data => { something }
Run Code Online (Sandbox Code Playgroud)

然后我想确保在调用之前它已被订阅 unsubscribe()

小智 5

我有一个类似的案例,我有一个 if 条件和一个可选订阅:

if (languageIsSet) {
   // do things...
} else {
   this.langSub = this.langService.subscribe(lang => { 
      // do things...
   });
}
Run Code Online (Sandbox Code Playgroud)

如果你想安全地调用取消订阅(你不知道是否已订阅),只需使用 EMPTY 实例初始化订阅即可:

private langSub: Subscription = Subscription.EMPTY;
Run Code Online (Sandbox Code Playgroud)

现在您可以毫无错误地取消订阅。


Har*_*oad 5

看来您可以检查订阅是否已关闭

this.subscription.closed
Run Code Online (Sandbox Code Playgroud)

指示此订阅是否已取消订阅。


mar*_*tin 2

您可以检查是否Subject有观察者,因为它具有公共财产observers

对于Observables 你不能,因为它们通常没有观察者数组。例如,仅当您通过运营商对它们进行多播时Subjectmulticast()

也许如果你能更详细地描述你的用例,我就能给你更好的建议。

const source = ...;
let subscribed = false;

Rx.Observable.defer(() => {
    subscribed = true;
    return source.finally(() => { subscribed = false });
})
Run Code Online (Sandbox Code Playgroud)