Execute a function when an RXJS Observable has completed its operation

Using the RXJS Observable has been smooth sailing so far, but I now find myself needing to not only react to observer.next() but also when observer.complete() is called. How can I capture the OnComplete event of an RXJS Observable? The documentation for RXJS seems unclear on this matter.

export class Service {
    myMethod():Observable<any> {
        return Observable.create((observer:any) => {
            for(let i=0; i<10; i++) {
                observer.next(i);
            }
            if(true==true) {
                // It's this event that I require
                observer.complete();
            } else {
                observer.error(xhr.response);
            }
        }
    }

export class Component() {
    // constructor etc.

    doSome() {
        this.service.myMethod()
        // Here I want to receive the OnComplete event
          .catch(this.handleError)
          .subscribe((num:any) => {
            console.log(num);
        });
    }
}

Answer №1

When using the subscribe method, three callbacks can be implemented. The third callback is specifically for the complete event.

executeAction() {
  this.service.myMethod()
      .subscribe((num:any) => {
        console.log(num);
      }, (err) => {
        this.handleError(err);
      }, () => { 
        this.handleComplete();
      });
}

Alternatively, the finally operator can also be applied in the following way:

executeAction() {
  this.service.myMethod()
      .catch(this.handleError)
      .finally(this.handleComplete) 
      .subscribe((num:any) => {
        console.log(num);
    });
}

NOTE: There is a distinction between the two examples especially when handling errors: Adding console.log statements would reveal that only handleError is executed in the first scenario.

-> handleError

In the second scenario, we see:

-> handleError
-> finally

To summarize, the finally method will always be called, whereas the complete may not be triggered.

Answer №2

According to Thierry Templier's suggestion, a possible approach is to make use of the finally/finalize operators (check out the rxjs documentation) (but bear in mind that this differs from utilizing the complete event, as noted).


last

An alternative method for executing actions on completion is by using the last operator (view more details at rxjs/last)

https://i.sstatic.net/eUgB8.png

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

Trouble accessing the Ionic SQLite database: Unable to open

I encountered some errors while attempting to connect my ionic app to a database. I am currently running the app on an android device using Google Chrome DevTools to troubleshoot the issue. Check out the createDatabase() function and the specific error th ...

Linking to a file within an npm package

Is it possible to reference local files within an npm package? Will these references still work correctly when the package is installed by a different consumer? For example, let's say I have developed an npm package for Angular which includes some HTM ...

Is there a way to prevent QtLinguist from opening every time Visual Studio tries to display a TypeScript file?

Ever since I installed Qt tools for Visual Studio, my Ctrl+click on a class name triggers Qt Linguist: https://i.stack.imgur.com/USAH1.png This hinders me from checking type definitions, even though Visual Studio has already parsed them. The type informa ...

Nest JS Guards - Employ either of two approaches

I have implemented two different JWT based strategies in my application: The first strategy involves single sign-on for organization members, where an external provider generates a JWT. The second strategy is for email/password authenticated external user ...

Combine two or more Firebase Observables

Currently, I am working on creating an Observable using FirebaseObjectObservable. However, before I can accomplish this, I need to query a Firebase list to obtain the key IDs required for the FirebaseObjectObservable. The structure of my data is as follow ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

Steps for subscribing to an Observable in a Jasmine unit test

I am currently working on incorporating mock json data into my unit tests by creating a utility function for other test files to utilize. Here is an example of how it can be implemented: @Injectable({providedIn: 'root'}) export class MockUtilsSer ...

Tips for ensuring the HTML checkbox element is fully loaded before programmatically selecting it

When a user accesses the page, I want certain checkboxes to be automatically checked. To achieve this, I am storing the IDs of the HTML checkbox elements in a service. Upon entering the page, the service is utilized to retrieve an array containing these ID ...

Encountered an error while trying to run the command "lite-server" in Angular 2

I recently had a machine where I installed Zsh and OhMyZsh, but later on uninstalled them. However, now whenever I try to run "npm start" on the Angular 2 Quick Starter template, I keep encountering this error message: Error occurred when executing comma ...

What is the proper way to retrieve a constant variable within a return statement?

Here is the code I have written: const keyToDisplayMessage = 'REGULAR_HOME'; const cf = format( { accountName: this.accountName, }, this.pageData.sucessMessages.keyToDisplayMessage, this.$route.name ); return cf; The ...

Angular9 integrated with Firebase to enhance the capabilities of

I am facing an issue with displaying a specific element from the database. //component.html <section class="firee"> <figure class="snip1208"> <div *ngFor="let scholarship of scholarships" > <h3>{{scholarshi ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

The AuthGuard (Guard decorator) is unable to resolve its dependencies according to Nest

My AuthGuard is responsible for checking the JWT token in controllers. I am trying to use this Guard in controllers to verify authentication, but I encountered the following error: Nest cannot resolve dependencies of the AuthGuard (?, +). Please ensur ...

Interacting between components using Angular 2 services

I am attempting to implement bidirectional service communication using Angular. I have followed the instructions provided in the documentation here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service interactio ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

Using a global CSS file in Angular can lead to large module bundles being emitted by Webpack

In our Angular application generated with angular-cli, we are utilizing various global styles and imports defined in the styles.scss file (which begins with /* You can add global styles to this file, and also import other style files */ if that sounds fami ...

The name "Identifier" has already been declared before

I am currently working on a social network project to enhance my skills in nodejs and reactjs. While debugging the backend code for /signin using Postman, I encountered an error that prevents me from launching the node server. The error message displayed i ...

Using TypeScript with Node.js: the module is declaring a component locally, but it is not being exported

Within my nodeJS application, I have organized a models and seeders folder. One of the files within this structure is address.model.ts where I have defined the following schema: export {}; const mongoose = require('mongoose'); const addressS ...

Exploring the routing hierarchy in Angular: Setting up parent and child

I'm completely new to Angular and I am in need of assistance with routing. The structure of my folders is as follows: There are two distinct layouts in my application - one for the login page, and another for the main admin page complete with sidebar ...

Unable to assign the value 'hello' to an undefined property in TypeScript

I'm attempting to define a class in TypeScript, but I keep encountering the error shown below. Here is the execution log where the error occurs: [LOG]: "adding" [LOG]: undefined [ERR]: Cannot set property 'hello' of undefined class Cust ...