David ROSEY
David ROSEY

Reputation: 1805

Rxjs actions on observable start (opponent of finalize)

On my current Angular project I need to do specific actions when subscribing to an observable. Thus I'm looking for, let's say, the opponent of finalize operator. Finalize operator call a function when observable completes or errors. In my case I need to call a function when the observable start. => Do you know how I can si this ?

Update to clarify my request: In a service I have an init methode returning an Observable. Thanks to pipable operator all the logic is iniside the observable because the initObservable may be subscribed in several components (avoid code duplication) simultaneously (that's why I use share operator) ex:

private initObs$: Observable<Data> = htttp.get('URL form where I get Data').pipe(
    tap(// do stuff with Data (init the store with Data in my case)),
    catchError(//Error handeling),
    finalize(// do onComplete actions ex: hide spiner overlay),
    share() // As this observable may be subscribed simultaneously by different subscriber
);

As this Obsevable may be subscribed in different components and simultaneously, I want to add the action of showing the spinner Overlay inside the Observable itself to avoid code like below in every components:

this.spinnerservice.show();
this.DataService.initObs$.subscribe();

Thanks in advance

Upvotes: 3

Views: 1843

Answers (1)

bryan60
bryan60

Reputation: 29325

you're looking for defer:

initObs$ = defer(() => {
  // do whatever, show spinner etc
  return htttp.get('URL form where I get Data').pipe(
    tap(// do stuff with Data (init the store with Data in my case)),
    catchError(//Error handeling),
    finalize(// do onComplete actions ex: hide spiner overlay)
  );
}).pipe(share());

Upvotes: 2

Related Questions