What is the method to cancel an Observable subscription without having a reference to the object of type "Subscription"?

If I were to subscribe to an Observable without an object of type "Subscription," how can I properly unsubscribe from it?

For instance, if my code looks something like this:

this.subscription = bla ... 

I know I can easily unsubscribe using the following method within ngOnDestroy():

this.subscription.unsubscribe();

But what happens when my code looks more like this:

 ngOnInit() {

    this.isLoggedIn$ = this.authService.isLoggedIn();

    this.isLoggedIn$.subscribe(res => {
      if (res) {
        this.isLoggedIn = true;
      } 
      else {
        this.isLoggedIn = false;
      }
    });

  }

How do I go about unsubscribing in this scenario? Is it even necessary to unsubscribe? If not, why is that so?

Answer №1

If you want to stop receiving notifications from an observable, there are 3 different ways to do so.

  1. An inefficient method is to explicitly unsubscribe every time you subscribe using this.subscription. It's recommended to avoid this approach.

  2. Another approach is to use the `takeWhile` pipe as demonstrated below:

    private isAlive = true;
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
      
      this.subscription = this.isLoggedIn$
       .pipe(takeWhile(() => this.alive))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    
    }
    
    ngOnDestroy() {
       console.log('[takeWhile] ngOnDestory');
       this.alive = false;
    }
    
  3. Alternatively, you can utilize the `takeUntil` operator:

    private unsubscribe: Subject<void> = new Subject();
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
      
      this.subscription = this.isLoggedIn$
       .pipe(takeUntil(this.unsubscribe))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    }
    
    ngOnDestroy() {
      this.unsubscribe.next();
      this.unsubscribe.complete();
    }
    

I trust that this information has been of assistance!

Answer №2

Your response includes the answer: bla ... is equivalent to your

this.isLoggedIn$.subscribe( ... )
function call.

ngOnInit() {

  this.isLoggedIn$ = this.authService.isLoggedIn();

  this.subscription = this.isLoggedIn$.subscribe(res => {
    if (res) {
      this.isLoggedIn = true;
    } 
    else {
      this.isLoggedIn = false;
    }
  });

}

Answer №3

Make sure to verify the existence of this.isLoggedIn$ before calling unsubscribe

ngOnDestroy() {
if (this.isLoggedIn$) {
this.isLoggedIn$.unsubscribe();
}
}

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

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

Is there a deeper philosophical rationale behind choosing to use (or not use) enums in TypeScript, along with string union types?

Recently, I delved into the world of enum and const enum in Typescript, causing some confusion. I grasped that const enum gets transpiled into simple values while regular enums do not. I also recognized certain distinctions between using string union type ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Can a React.tsx project be developed as a standalone application?

As a student, I have a question to ask. My school project involves creating a program that performs specific tasks related to boats. We are all most comfortable with React.tsx as the programming language, but we are unsure if it is possible to create a st ...

Unsupported method 'keys' for the specified object - (Internet Explorer 11)

I'm having trouble identifying the issue in Internet Explorer 11. The application functions perfectly without any problems in other browsers such as Chrome and Firefox. https://i.stack.imgur.com/5QvML.png ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Sliding toggle in Angular Material2 Menu

How can I properly include a Slide-toggle <mat-slide-toggle> within a Menu <mat-menu>? In addition, when I toggle the Slide-toggle, the menu closes. Is there a way to prevent this behavior? <mat-menu #menuSettings="matMenu"> ...

Connecting Ionic 3 with Android native code: A step-by-step guide

I just finished going through the tutorial on helpstack.io and was able to successfully set up the HelpStackExample with android native based on the instructions provided in the GitHub repository. The only issue is that my company project uses Ionic 3. H ...

The 'append' property is not present in the 'Headers' type in Angular 2

import { HttpClient, HttpHeaders } from '@angular/common/http'; export class LoginService { let headers: HttpHeaders = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json'); } I encounter ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Issue with Angular 5 template: "AbstractControl type does not contain property 'length'"

While attempting to compile my Angular project using the command ng build --prod --output-path <my_destination_path>, I encountered a few errors like the following: ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Proper ...

What is the correct way to bring in a utility in my playwright test when I am working with TypeScript?

I am working on a basic project using playwright and typescript. My goal is to implement a logger.ts file that will manage log files and log any logger.info messages in those files. To set up my project, I used the following commands and created a playwri ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

I'm currently working on creating an online store using Next.js and TypeScript, but I'm struggling to effectively incorporate my fake product data array into the site

"using client" import Container from "@/components/Container"; import ProductDetails from "./ProductDetails"; import ListRating from "./ListRating"; import { products } from "@/utils/products"; interface I ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

What is the method for retrieving the index of an enum member in Typescript, rather than the member name?

Here is an example of how to work with enums in TypeScript: export enum Category { Action = 1, Option = 2, RealEstateFund = 3, FuturesContract = 4, ETFs = 5, BDRs = 6 } The following function can be used to retrieve the enum indexe ...

Discovering the class type in TypeScript

In my TypeScript coding journey, I encountered a challenge in detecting a specific Class type. Despite its seeming simplicity, I found a lack of straightforward documentation on how to accomplish this task. Here is an example that illustrates the issue: Cl ...

Typescript's Type Specification

I am currently working with NextJs and Typescript and I am facing an issue. Whenever I include the "any" keyword in my code, it renders correctly. However, if I remove it, I encounter errors with post._id, post.title, and post.body. Challenge: Can someon ...