首页 > 解决方案 > How to stop observers in Observable.merge?

问题描述

I have a method that creates timer:

 create(options: any) {
    return timer(0, 1000).pipe(
      map(() => {
        return options;
      }),
      takeWhile(() => new Date() < options.finishDate)
    );
  }

Then this timer I add to array this.timers of Observables:

this.timers.push(this.create({finishDate: new Date()}))

When I merge observers:

this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
   console.log(x);
});

I see that console.log(x); continues work despite timer was finished.

Why? And how to stop all timers in array?

I can unsubscribe here:

 Observable.merge(this.timers).subscribe(x => {
   x.unsubscribe();
});

But it does not stop Observable.merge.

标签: javascriptrxjsrxjs5rxjs6

解决方案


this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
   console.log(x);
});

In this case mergeObserver is not an observable but a subscription. The subscribe method returns a subscription. So renaming this to mergeSubscription and calling unsubscribe on this object is how to unsubscribe.

If you want a reference to the observable you need to subscribe after you have taken a reference.

this.mergeObserver = Observable.merge(this.timers);

this.mergeSubscription = this.mergeObserver.subscribe(x => {
   console.log(x);
});

and then you unsubscribe with the mergeSubscription object.

Observable.merge(this.timers).subscribe(x => {
   x.unsubscribe();
});

Here you cannot call unsubscribe on x as x is the value that comes out of the merged timers. When one of the timers emits then the merge will emit that value as well, it is just a number and does not have an unsubscribe method.


推荐阅读