intelis
intelis

Reputation: 8058

Unsubscribe all listeners from Observable

I'm new to Observables and Typescript so this might be a rookie question. I want to build a simple timer but I want to be able to unsubscribe all subscribers within the timer itself.

My code so far, looks like this.

import { Observable } from "rxjs/Rx";

export class Timer {

    private interval: number;
    private ticker: Observable<any>;

    constructor() {
        this.interval = 1000; // Miliseconds
        this.ticker = Observable.interval(this.interval).timeInterval();
    }

    complete() {
        // Unsubscribe all listeners
    }
}

How can I unsubsribe all listeners from complete method?

Upvotes: 2

Views: 440

Answers (1)

martin
martin

Reputation: 96891

You can't unsubscribe observers yourself if you don't have their Subscription objects (returned from .subscribe() calls).

However, you can do it the other way around and instead complete the source Observable using the takeUntil operator which will dispose the chain and unsubscribe all observers.

constructor() {
  this.end = new Subject();

  this.ticker = Observable.interval(this.interval)
    .takeUntil(this.end)
    .timeInterval();
}

...

complete() {
  this.end.next();
}

Upvotes: 1

Related Questions