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

Constantly visible scrolling feature on material side navigation

Is there a way to keep the scroll bar in the sidenav always visible, even when the content is within the Y axis limits? This would prevent the scroll bar from fading in and out every time I open or close one of the mat-menu-items that function as accordio ...

What are the steps to utilize kendo-fileselect in order to upload files from an Angular application to a C# web API?

We are integrating Kendo for Angular into our current project. In our existing system, we utilize kendo-upload which triggers a server call immediately. However, we cannot follow the same approach for this particular page. https://i.stack.imgur.com/qdn2b. ...

The function tokenNotExpired encounters an error when attempting to access the localStorage, as it

I am looking to incorporate the angular2-jwt library into my project: https://github.com/auth0/angular2-jwt However, I encountered an exception when attempting to call the tokenNotExpired function: Exception: Call to Node module failed with error: Refe ...

Error during Webpack Compilation: Module 'jQuery' not found in Travis CI with Mocha Test

I've been struggling to automate tests for my repository using mocha-webpack and Travis CI. The local machine runs the tests smoothly, but Travis CI hasn't been able to complete them yet due to an unresolved error: WEBPACK Failed to compile wit ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

Sending an ArrayBuffer from Angular to Electron results in the window crashing

In my Electron application, I have integrated an Angular application internally. I am trying to download a byte array (ArrayBuffer) via an API call and then passing this data to a method connected through electron.remote.require('./file-service') ...

Error encountered while compiling an Asp.Net Core project due to exceeding the maximum allowable path length in the

Encountering a critical error during the build process with Visual Studio 2016 update 3 Asp.Net Core. The build is interrupted with the following message: Severity Code Description Project File Line Suppression State Error MSB4018 The "FindC ...

Retrieve the selected rows in AG grid based on their group index

Important: The data in the grid is organized into groups. I am attempting to retrieve selected rows at a specific group index. I have attempted using the getDisplayedRowAtIndex(index).allLeafChildren method and looping through each node to find those tha ...

How to utilize TypeScript fetch in a TypeScript project running on node with Hardhat?

During a test in my hardhat project on VSCode, I encountered the need to retrieve the metadata object of my NFT from a specified URL. Initially, I assumed I would have to import fs to read the URL. However, while typing out the method, I impulsively opted ...

Encountering a NoEmit error with .d.ts files when using Webpack, tsconfig, and dynamic imports

I'm struggling to grasp the interaction between webpack, tsconfig, and .d.ts files in my project. This is how my project structure looks: The ScriptsApp directory includes an @types folder structured like this: Here's my tsconfig.json configur ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

Retrieve a mapping of keys from a generic object structure in TypeScript

I am trying to extract the key map from an object, and although I have created a function for this purpose, TypeScript is not happy with it. How can I resolve this issue without using acc: any? const origin = { a: 1, b: 'string', c: () =&g ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

.bail() function does not function properly when used in conjunction with express-validator

While registering a new user, I require their name, email, and password. If no name is provided, there is no need for the backend to validate the email. I believe that the use of .bail() in express-validator should handle this situation, but unfortunately ...

Tips for retrieving the body of a response in string format

My project involves an HTTP service that sends requests to the server and receives responses. Sometimes, different errors occur on the server during development which do not always return JSON. In such cases, I need to retrieve the response body as a strin ...

Angular 7 and Spring 5 are being hindered by CORS restrictions

I'm currently working on a project that involves Spring 5 with Spring Security and Angular 7. I am facing an issue while trying to connect the frontend, receiving the following error message. It's worth mentioning that the backend and frontend pr ...

Angular tutorial: Display EmployeeName on Label by verifying EmployeeCode

Within my Angular-14 project, I am working with the following code: component.ts: constructor( private fb: FormBuilder, private employeeService: EmployeeService, private bsModalRef: BsModalRef, private modalService: BsModalService ) { ...

Tips for capturing your desktop screen within an angular 2+ application

I am in need of a solution to share my desktop screen using Angular 6. I have done some research to find the right package for this feature but have been unsuccessful so far. I came across various packages such as RecordRTC, Aperture, and screen-capture-r ...