Is there a gap in the Nativescript lifecycle with the onPause/onResume events missing? Should I be halting subscriptions when a page is navigated

My experience with NativeScript (currently using Angular on Android) has left me feeling like I might be overlooking something important.

Whenever I navigate to a new route, I set up Observable Subscriptions to monitor data changes, navigation changes, and service updates. However, NativeScript keeps a stack of loaded routes in memory.

The issue arises when one of my services triggers a change - even if the corresponding route is hidden deep in the back stack, its subscriptions still get executed. This behavior makes me question why these hidden routes remain active, hinting at a potential memory leak.

This leads me to wonder why NativeScript lacks an onResume & onPause logic similar to that in the Android SDK. With such functionality, I could easily start or stop observers as needed.

In an attempt to address this concern, I've tried utilizing the following code:

ngOnInit() {
    console.log('onInit');
}

@HostListener('loaded')
onResume() {
    console.log('onResume');
}

@HostListener('unloaded')
onPause() {
    console.log('onPause');
}

ngOnDestroy() {
    console.log('onDestroy');
}

Despite my efforts, I can't shake off the feeling that I may not be the right person to manage this situation, and that it should ideally be handled by NativeScript's internal SDK. Thank you for your input.

Answer №1

For more information on Angular navigation in NativeScript, check out this page from the NS Angular docs:

Pay special attention to this section:

In a native mobile application, navigated views remain active to preserve their view state for when you return to them. Views are only destroyed when navigating away from them. The page-router-outlet handles native navigations and its components must align with the lifecycle of native views using the custom NSRouteReuseStrategy.

To handle unsubscribing, I utilize a BaseComponent that tracks subscriptions for components and removes them in the ngOnDestroy method, ensuring they are eventually cleaned up.

In certain situations, it may be necessary to manage subscriptions in the NativeScript lifecycle hooks, such as page.on('navigatedFrom'), if specific actions need to be taken.

Answer №2

Activated or deactivated are events triggered on {N} View. It serves as the foundational component, inherited by all other components within the framework. The activated event occurs when the underlying native view is created, while the deactivated event typically occurs when it is destroyed or removed from the screen.

Your Page (any component designated for a route path is encapsulated within a Page in Angular) functions as a fragment. As you navigate forward using page-router-outlet, your current page is placed onto a back stack (history). The deactivated event may also be triggered at this juncture, but it does not necessarily require an unsubscribe action. Since the component remains active on the back stack, the activated event will be invoked again upon navigating backward.

I recommend sticking with ngOnInit for subscribing and ngOnDestroy for unsubscribing, just like managing Angular web applications. Reserve the use of the activated event for situations necessitating access to UI elements or their underlying native components. Keep in mind that this event triggers each time the page loads, including during back navigation. Therefore, promptly remove the loaded listener once its purpose is fulfilled to prevent redundant executions during back navigation.

Maintaining active subscriptions while the component is on the back stack should not significantly impact performance. Typically, the native view remains unchanged unless actively engaged. However, consider unsubscribing in scenarios involving resource-intensive operations in the controller, such as complex mathematical computations or lengthy loops. Ultimately, the decision to unsubscribe depends on the nature of activities performed within the subscription.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

Angular demo showcasing a Multi-Column ListView component in NativeScript

I have a question that may seem simple to you, but I haven't been able to find a straightforward example anywhere. I came across this resource already, but it's not in Angular. As a beginner in Nativescript (I've been working with it for a ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

When ng-test is executed in an Angular service, the function array.some is not found

After retrieving allUsers from the cache and initializing it, I then set the boolean value of specialUserExists based on a condition in allUsers using allUsers.some() (reference to the Array.prototype.some() method). service.ts @Injectable({ providedIn: ...

Enabling CORS Access-Control-Allow-Origin for secure HTTPS connections

Currently, I am working on a dual-part application. The first part includes an HTTPS API server on AWS Elastic Beanstalk, utilizing CloudFront. The second part consists of an HTTPS AWS S3 Angular frontend, also leveraging CloudFront. In the API app.js, I ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

How can I invoke the header component function in another component using Angular 2?

Is there a way to invoke the showmodel(displayType) function from another component? How can I call a function in the header component from a different component? header.component.ts import { Component,Renderer } from '@angular/core'; i ...

Encountering notifications and issues pertaining to conflicting dependencies after integrating the angular-oauth2-oidc dependency into the package.json file

I am currently working on an Angular project and wanted to share my package.json file for reference: { "name": "angular.io-example", "version": "0.0.0", "description": "Example project from ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

Preventing the compilation process from overwriting process.env variables in webpack: A step-by-step guide

Scenario I am currently working on developing AWS Lambda functions and compiling the code using webpack. After reading various articles, I have come to know that the process.env variables get automatically replaced during compilation. While this feature ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...

Issue encountered: Unable to access the property 'loadChildren' as it is undefined, while attempting to configure the path

How can I conditionally load the route path? I've attempted the code below, but it's throwing an error. Can someone guide me on how to accomplish this task? [ng] ERROR in Cannot read property 'loadChildren' of undefined [ng] i 「w ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Leveraging Webworkers in an Angular application for efficient data caching with service workers in the Angular-CLI

I am looking to run a function in the background using a worker, with data coming from an HTTP request. Currently, I have a mock calculation (e.data[0] * e.data[1] * xhrData.arr[3]) in place, but I plan to replace it with a function that returns the actual ...

The ASP.NET Core Web API is designed to handle incoming dates that are one day in the past, as sent by

After selecting a date from an Angular material datepicker, the ASP.NET Core Web API consistently receives the date as one day earlier. The date being sent is obtained from a form control and assigned to a property like so: scheme.date1 = this.formControl ...

Error: Attempting to access a property called 'sign' on an undefined value

I encountered an issue while signing my transaction where I received an error message stating sendTransaction needs signer. Even though both message (encrypted using keccak256) and signer have values, I am unsure why there is a problem when executing the w ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...