Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs - do something when observable starts executing

Tags:

angular

rxjs

Is there a way to attach a handler when an observable starts executing (someone called subscribe on it)?

like in angular:

    this.http.post('someUrl', resource).pipe(
       catchError(),
       finalize((() => this.hideLoader()),
       **executing(() => this.showLoader()) <------**
    )
like image 423
Lerner Avatar asked Apr 11 '18 19:04

Lerner


People also ask

What does an Observable return?

An Observable Allows its Observers to Unsubscribe The subscribe() method returns a subscription object which may be used to cancel the subscription. Calling unsubscribe() clears the resources used by the subscription and calls the teardown function returned by the subscriber function.

Why use subject instead of Observable?

In comparison to a regular Observable, a Subject allows values to be multicasted to many Observers. A Subject and its subscribers have a one-to-many relationship. A Subject can be an Observable as well as an Observer. They hold a registry of many listeners to multiple Observables.

How do I use RxJS defer?

defer allows you to create an Observable only when the Observer subscribes. It waits until an Observer subscribes to it, calls the given factory function to get an Observable -- where a factory function typically generates a new Observable -- and subscribes the Observer to this Observable.

What is the difference between Observable and promises?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time.


1 Answers

The defer observable factory function is most likely what you are looking for:

import { defer } from 'rxjs';

const post = defer(() => {
  this.showLoader();
  return this.http.post('someUrl', resource).pipe(
    catchError(),
    finalize(() => this.hideLoader())
  );
});
post.subscribe();
like image 197
cartant Avatar answered Sep 27 '22 21:09

cartant