Last active
April 1, 2024 20:54
-
-
Save BenBestmann/4dfb6a9ae7cd1bf52d22e07291c907f3 to your computer and use it in GitHub Desktop.
React Suspend behavior for RXJS Observables. Handles the suspension of emitted values of the source observable by prepending values for loading and error states.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function suspend<T>(): OperatorFunction<T, SuspendedValue<T>> { | |
return (source: Observable<T>) => | |
source.pipe( | |
map((next) => ({ | |
value: next, | |
isLoading: false, | |
error: null | |
})), | |
catchError((error) => of({ error, isLoading: false, value: null })), | |
startWith({ isLoading: true, value: null, error: null }) | |
); | |
} | |
// Usage Example | |
const data$ = this.http.get<Config>('url').pipe(suspend()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment