maruthi rudra
maruthi rudra

Reputation: 1

How to stop the Observable.timer which is used through observable operators like debounceTime and switchMap for asynchronous validations

I need to stop the Observable.timer when I navigate from that page to another page. Below is the code which I'm using in my project.

import { Component, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import {Observable, Subject}from 'RxJs/Rx';

export class SettingsPage extends BasePage implements OnDestroy {
ionViewDidLoad() {
let initial: boolean = true;

this.serverUrlStream
        .debounce((val)=> Observable.timer(initial ? 0 : 500))  
        .switchMap(val => {     
                this.canLeave = false;  
                this.apiClientService.ocServiceUrl = val;
                return Observable.fromPromise(this.apiClientService.getHospitals());
        })
        .catch((err, caught)=>{
            console.log(err);
            return caught;  // Continue after error
        })
        .subscribe((hospitals: Hospital[]) => {
            this.hospitals = hospitals;
            if (hospitals.length > 0) {
                this.settings.hospitalInstallId = hospitals[0].InstallId;
                this.canLeave = true;                   
                this.cd.detectChanges();
            }
        });


    this.serverUrlStream.next(this.settings.serverUrl);
    initial = false;
}
//I tried like below to stop the timer when I left from this page.

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

}

Above code is not working still ajax call is running every 5 seconds. Can anyone please help me to stop the Observable.timer when user leave the current page

Upvotes: 0

Views: 920

Answers (1)

CitizenNito
CitizenNito

Reputation: 326

Your approach with unsubscribing in ngOnDestroy is the correct one. You just got the syntax slightly wrong.

You first need to assign the actual subscription to a variable, like this this.serverUrlSubscription = this.serverUrlStream.debounce(...)...subscribe(...);

where you should declare serverUrlSubscription: Subscription; as a member of your class first (Subscription type can be imported from rxjs/Subscription).

You can then simply do this.serverUrlSubscription.unsubscribe(); in your ngOnDestroy to detach and destroy the subscription.

A second approach would be to use takeUntil(this.router.events.filter((event) => event instanceof NavigationStart) after the switchMap operator, where you'd first have to inject the angular router to this.router.

But i would recommend you use ngOnDestroy.

Upvotes: 1

Related Questions