rxjs - do something when observable starts executing
you could wrap the http.post observable in a Observable.create, and execute the logic you want there:
const wrapped$: Observable<any> = Observable.create((observer:
Observer<any>) => {
showLoader();
http.post('...').subscribe(
value => observer.next(value),
error => observer.error(error),
() => observer.complete()
)
});
wrapped$.subscribe() // and subscribe to this source instead
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();
A bit prettier way to do the same as in previous suggestions:
const withLoader$ = of(null).pipe(
tap(() => showLoader()),
switchMap(() => this.http.post('someUrl', resource)),
finalize(() => this.hideLoader())
);
Advanced sample bellow:
apply(observable: Observable<any>): Observable<any> {
return of(null).pipe(
map(() => this.show()),
switchMap((pbKey: string) => observable.pipe(
finalize(() => this.hide(pbKey))
))
);
}