How to unsubscribe/stop Observable?

Viewed 19032

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

4 Answers

The best way is to unsubscribe when instance is destroyed.

ngOnDestroy() {
 this.sub.unsubscribe();
}

I have not yet worked with the timer yet but I think the concept still works. The approach I used was working with a service.

(the work is based on: https://medium.com/angular-in-depth/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0)

  1. Create my new BehaviorSubject<T>(T).
  2. Create a new Subscription() object.
  3. wrap subscriptions with the addSubscription method.
  4. when the parent or higher component gets destroyed ngOnDestroy(): void unsubscribe

Service

private organisation = new BehaviorSubject<__Organisation>(newOrganisation);
organisation$ = this.organisation.asObservable();

private organisationSubscription: Subscription = new Subscription();

Service Methods

addOrganisationSubscription(subscription: Subscription): void {
    this.organisationSubscription.add(subscription);
}
unSubscribeOrganisation(): void {
    this.organisationSubscription.unsubscribe();
}

addOrganisationSubscription(subscription: Subscription): void {
   this.organisationSubscription.add(subscription);
}

Component

this.organisationService.addOrganisationSubscription(
      this.organisationService.organisation$.subscribe(
      ...
      )
)

ngOnDestroy(): void {
    this.organisationService.unSubscribeOrganisation();
}

So after some PUNISHING research I've added my own npm library for this problem.

Improves previous answer by NOT having to add any extra convolution variables and ease of use.

enter image description here

Related