Allow finalize
to not be executed on unsubscription
#7187
Replies: 5 comments 2 replies
-
Something like this? import { MonoTypeOperatorFunction, tap } from 'rxjs';
function finished<T>(callback: () => void): MonoTypeOperatorFunction<T> {
return tap({ complete: callback, error: callback });
} |
Beta Was this translation helpful? Give feedback.
-
well almost 😄 your solution with |
Beta Was this translation helpful? Give feedback.
-
Is there any reason why it couldn't be like the one below? It feels more reactive to me than relying on const clickEvent$ = new Subject();
const loadData$ = clickEvent$.pipe(switchMap(() => of(Math.random()).pipe(delay(1000))));
const isLoading$ = merge(
clickEvent$.pipe(map(() => true)),
loadData$.pipe(map(() => false)),
).pipe(
startWith(false),
distinctUntilChanged(),
); |
Beta Was this translation helpful? Give feedback.
-
to clarify - I know that what I want is achievable by other means than |
Beta Was this translation helpful? Give feedback.
-
I know that I use this.clicks$
.pipe(
tap(() => showLoadingSpinner()),
switchMap((click) =>
loadData() // loadData() returns observable that loads data
.pipe(
finalize(() => hideLoadingSpinner(), true), // hide spinner when loading finishes or errors
)
)
.subscribe((data) => {
// do something with data
}) |
Beta Was this translation helpful? Give feedback.
-
It wouldd be nice if it was possible to instruct
finalize
to not execute on unsubscription. Currentlyfinalize
is executed when source observable terminates with complete or error and also when its unsubscribed.Imagine a use case where user clicks trigger other observable, for example to load some data. This is usually handled by
switchMap
ing, so when user clicks again while previous data is loaded, it is cancelled (unsubscribed) and only new data is being loaded. Usually in such case there are some side effects to indicate loading is in progress.in case above the
loadingSpinner
will be hidden when clicked while data is loading, becauseswitchMap
's unsubscription ofloaddata()
causesfinalize
callback to be executed. However in this case we dont want that, we want to execute the callback only whenloadData()
finishes or errors, not when unsubscribed.Adding optional argument to
finalize
that would disable callback execution on unsubscription, would be handy.Beta Was this translation helpful? Give feedback.
All reactions