Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs actions on observable start (opponent of finalize)

Tags:

angular

rxjs

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

like image 378
David ROSEY Avatar asked Oct 17 '25 17:10

David ROSEY


1 Answers

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());
like image 165
bryan60 Avatar answered Oct 20 '25 07:10

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!