Misanthropist
Misanthropist

Reputation: 211

How to destroy applicationOn events for Nativescript lifecycles in Angular

In my Nativescript + Angular phone app, I have managed to listen to suspend and resume events by placing them into the constructor as follows:

export class HomeComponent {
    constructor(private router: RouterExtensions,
            private tokenService: TokenStoreService) {

        applicationOn(suspendEvent, (args: ApplicationEventData) => {
            tokenService.bioScanSetAuthenticated(false);
            tokenService.setLastRoute(this.router.router.url);
        });

        applicationOn(resumeEvent, (args: ApplicationEventData) => {
            if (this.tokenService.bioScanIsAuthenticated()) {
                return;
            }
            this.router.navigate(['/login'], { animated: false, clearHistory: true });
        });
    }
}

This works great and the app behaves as expected, however when logging comments to the console output from within these applicationOn methods I notice that each time an additional comment is being made whenever the app is suspended and resumed. This indicates that the applicationOn events are being recreated each time the class is loaded rather than being destroyed.

Is there a better way of doing this?

Upvotes: 0

Views: 535

Answers (1)

Manoj
Manoj

Reputation: 21908

I would recommend handling global events (like applicationOn) within a service with root scope which would probably be initialised only once. This service may host a Subject / Observable which would emit upon resume / suspend events.

But if you like a hot fix for your current problem, remove the event listeners in the destroy life cycle callback.

import { applicationOff as off } from from "tns-core-modules/application";

....

ngOnDestroy() {
    // This will remove all active event listeners at once, 
    // If you want to remove one particular listener, you will have to pass the function reference as second parameter
    applicationOff(suspendEvent);
    applicationOff(resumeEvent);
}

Upvotes: 2

Related Questions