Skip to content

Instantly share code, notes, and snippets.

@BenBestmann
Last active April 1, 2024 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenBestmann/4dfb6a9ae7cd1bf52d22e07291c907f3 to your computer and use it in GitHub Desktop.
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.
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