Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe/stop Observable?

I use the following code for timer:

export class TimerService {
  private ticks: number = 0;
  private seconds: number = 0;
  private timer;

  constructor(seconds: number) {
    this.seconds = seconds;
    this.timer = Observable.timer(2000, 1000);
    this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks === this.seconds) {
      this.timer.dispose();
    }
  }
}

When I try to stop timer in line:

this.timer.dispose(); // this.timer.unsubscribe();

It does not work for me

like image 390
OPV Avatar asked Jul 21 '17 09:07

OPV


People also ask

How do I cancel Observable subscription?

An Observable subscription has an unsubscribe() function to releases resources/memory or to cancel the observable execution. In the above example we have multiple subscription(). We have stored them in a subscription() array and we have unsubscribe() them one by one in ngOndestroy() as shown in the above example.

Do you need to unsubscribe from Observable?

In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.

How do I unsubscribe from RxJS Observable?

Unsubscribing Manually One method we can use, is to unsubscribe manually from active subscriptions when we no longer require them. RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .


1 Answers

The subscribe method returns a Subscription object, which you can later use to stop listening the stream contained by the observable to which you subscribed.

import { ISubscription } from 'rxjs/Subscription':
import { TimerObservable } from 'rxjs/observable/TimerObservable';

export class TimerService {
  private ticks = 0;
  private timer$: TimerObservable;
  private $timer : ISubscription;

  constructor(private seconds = 0) {
    this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method
    this.$timer = this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks >= this.seconds) {
      this.$timer.unsubscribe();
    }
  }
}

Its important to notice that unsubscribe exist in rxjs (version 5 and up), before that, in rx (version lower than 5, a different package) the method was called dispose

like image 112
Jota.Toledo Avatar answered Sep 27 '22 21:09

Jota.Toledo