How to call finally subscribing to observable with Rxjs and JavaScript?

Estimated read time 2 min read

In RxJS, you can use the finally operator to add a final action to be performed after an observable has completed or thrown an error. Here’s an example:

import { of } from 'rxjs';
import { map, catchError, finally } from 'rxjs/operators';

const myObservable = of('hello');

  map(value => value.toUpperCase()),
  catchError(error => {
    return of('default value');
  finally(() => {
    console.log('Observable complete');
  value => console.log(value),
  error => console.error(error)

In this example, myObservable emits a single value 'hello'. The observable is piped through the map operator to convert the value to uppercase, and the catchError operator to handle any errors and return a default value.

The finally operator is then used to log a message to the console when the observable completes, whether or not it completed successfully or with an error.

Finally, the subscribe method is called on the observable to actually start emitting values. The subscribe method takes two functions as arguments, one to handle the emitted values, and another to handle any errors.

So in summary, the finally operator is used within the observable pipeline to specify an action to be performed after the observable has completed, and the subscribe method is used to actually subscribe to the observable and start receiving emitted values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply