I'm attempting to create a function that wraps a given Observable and adds a loading screen to it.
The function
function addLoadingScreen<T>(obs$: Observable<T>): Observable<T>
should function like this:
- Show the loading screen.
- Execute the observable received as a parameter.
- Hide the loading screen after all values are emitted.
Initially, my implementation idea was:
function addLoadingScreen<T>(obs$: Observable<T>): Observable<T> {
return of(null).pipe(
tap(() => console.log("show loading screen")),
switchMap(() => obs$),
finalize(() => console.log("hide loading screen"))
);
}
However, when I chain other operators to the result of this function, the "hide loading screen" message is executed after those chains, not after the original observable finishes.
Here's an example: https://stackblitz.com/edit/rxjs-wrapping-observable
The result in the console above shows:
show loading screen
im reducing
im reducing
reducing finished so loading screen should be hidden
the result is 6
hide loading screen
What I'm striving for is:
show loading screen
im reducing
im reducing
hide loading screen
reducing finished so loading screen should be hidden
the result is 6