Can a custom finish method for a subscription automatically unsubscribe itself?

Creating an Observable:

public generateData(): Observable<any> {
    return this.fetchEndpoint()
      .pipe(
        switchMap((endpoint) =>
          this.http.retrieve<any>(endpoint)
        ),
        take(1)
      );
  }

Subscribing to the observable triggers the HTTP request

this.generateData().subscribe({
      next: result => this.result = result,
      complete: () => {
        this.performActions();
      },
    });

Since the Observable completes after emitting one value due to take(1), the complete method is executed, where additional actions are performed. As this method is custom, should I manually unsubscribe in the complete method or does it happen automatically?

Edit: How can I handle unsubscription in the complete method of the subscription?

Answer №1

There is no need to manually unsubscribe from a completed observable. Observables either complete naturally or with an error, according to their contract.

Let's look at an example to better understand this concept.

const sub = interval(250).pipe(
  take(4),
  map(x => x + 1)
).subscribe({
  next: console.log,
  complete: () => console.log("This observable completed naturally"),
  err: _ => console.log("This observable completed with an error")
});

console.log("Is subscription closed? " + sub.closed);

setTimeout(() => {
    console.log("Is subscription closed? " + sub.closed);
}, 1250);

Output:

Subscription closed? false
1
2
3
4
This observable completed naturally
Subscription closed? true

This demonstrates that observables that will complete themselves do not require manual unsubscribing and do not lead to memory leaks. The concern arises with long-lived observables (e.g., an interval without completion).

In Angular, some observables are tied to a component's lifecycle and must be unsubscribed when the component is destroyed to prevent memory leaks.


Synchronous Scenario:

of("Hello There").subscribe({
  next: console.log,
  complete: () => console.log("This observable completed naturally"),
  err: _ => console.log("This observable completed with an error")
});

You don't need to unsubscribe from this synchronous observable as it completes before you can even unsubscribe.

 const sub = of(1).subscribe();
 console.log(sub.closed); // output: true

Example Requiring Unsubscription:

const sub = interval(1000).subscribe(console.log);
setTimeout(() => {
    console.log("Is subscription closed: " + sub.closed);
    sub.unsubscribe();
    console.log("Is subscription closed: " + sub.closed);
}, 3600000);

In this case, we start an interval observable which runs indefinitely until explicitly unsubscribed after an hour.

Output:

0
1
2
... [skipping ahead]
3596
3597
3598
3599
Is subscription closed: false
Is subscription closed: true

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 header on the express req object is not persisting when navigating between routes

I have been struggling to set the sessionId in my express req object so that it can be accessed across different routes. Interestingly, when I try to set it using middleware, it works perfectly fine. However, when attempting to do the same within a route, ...

Establishing Communication Between Client and Server in ASP.net Using SignalR Technology

Hey everyone, having some trouble with my SignalR Client here. Every time I try to run it, I get this pesky error popping up: 0x800a139e - JavaScript runtime error: SignalR: Error loading hubs. It's telling me to check my hubs reference, so I need to ...

Neglecting to utilize a parameter in a function

Here's a question from a beginner: what if I create a function named sendRequest that accepts multiple parameters for an ajax call? I'm not really concerned about the ajax request itself, I just want to understand how the parameters work. funct ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...

Guide to importing VRML Files with three.js

I am encountering an issue with importing a VRML file in three.js. Below is the content of the VRML file: #VRML V2.0 utf8 #Created by CINEMA 4D DEF B1 Transform { translation 600 0 0.333333 children [ DEF _60_ Transform { translation -600 0 0 ch ...

Error encountered during module build in Vue loader version 17.0.0 with Webpack version 5.74.0

I am encountering an issue while trying to integrate vue-loader into my SPA VUE APP. The error message I'm receiving is as follows: ERROR in ./app2.vue Module build failed (from ./node_modules/vue-loader/dist/index.js): TypeError: Cannot read prope ...

Confirming Identity using Fetch

In my React application, I am utilizing Javascript to interact with a database table called "users" which contains a boolean field indicating the user type (such as patient, doctor, etc). My goal is to check if a user exists and is not classified as a "pat ...

Deno powered GraphQL server

For the code below, it only works once import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, buildSchema, } from "https://cdn.pika.dev/graphql/^15.0.0"; import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protectio ...

What is the best way to initiate JavaScript using a button click in WordPress?

I need to add a button to a WordPress page that triggers a JavaScript function when clicked. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> < ...

Issue with File Existence Resulting in ENOENT Error

Check out this gist for more information: https://gist.github.com/973e70bde8e6a530c489 I have encountered an interesting problem with two scenarios. In one scenario, I can parse a CSV file that is already on the box without any issues. However, in the oth ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

An issue has occurred: The type 'Observable<{}[]>' cannot be assigned to the type 'AngularFireList<any[]>'. This error is specific to Ionic framework

I encountered an issue while attempting to store data in the database as it is not getting saved and keeps showing errors. I am facing a problem with my .ts file where the code for this.tasks in the constructor is underlined in red, but I am unsure of th ...

Using a JQuery for loop to update the value of an input field based on the selected option's attribute, with only the last value

I need to simplify this lengthy code snippet, which is currently functioning well: $(document).ready(function() { $("#PayRate1").change(function() { $('#HourlyRate1').val($('option:selected', this).data('rate')); ...

Ways to stringify a JavaScript new date object using JSON

Extracting information from the form's JSON as users input data on the calendar const data = JSON.stringify(orderForm.informationDate)); At present, I am retrieving JSON data to generate a PDF document: {"year":2023,"month":12,&qu ...

Creating a JSoup document with embedded JavaScript: A step-by-step guide

After generating a JSoup Document with two <script type="application/javascript">/* .. */</script> elements, I encountered an issue. The Problem: Whenever I use .html() or .toString() in JSoup, my JavaScript code gets escaped. if (foo &&a ...

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

Ionic fails to update variables in the view

I have a query regarding Ionic 4 and why Angular doesn't update the view in real-time with the new alert controller. For instance, I have this simple code for a countdown timer that restarts when the timer finishes after clicking okay in the modal al ...

Trigger function in a different child component on mouse up

Trying to call a function in a child component from another child component in ReactJS. Specifically, I want to trigger a function in another component when the 'mouseup' event happens. Here is an illustration of what I am attempting to achieve: ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...