Skip to content

Instantly share code, notes, and snippets.

@buhichan
Last active April 15, 2021 07:58
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 buhichan/963a155d80eb4b1720c32ac0885b03cf to your computer and use it in GitHub Desktop.
Save buhichan/963a155d80eb4b1720c32ac0885b03cf to your computer and use it in GitHub Desktop.
rxjs-materialize-response.tsx
import { Observable, SubscribableOrPromise, OperatorFunction } from "rxjs"
import { switchMap, tap } from "rxjs/operators"
export type MaterializedResponseState<T> = { loading: true, error: null, value: null | T } | { loading: false, error: Error } | { loading:false, value: T }
export function materializeResponse<T1, T2>(performRequest: (t1: T1) => SubscribableOrPromise<T2>): OperatorFunction<T1, MaterializedResponseState<T2>> {
return (observer: Observable<T1>) => {
let lastResponse = null as null | T2
return new Observable<MaterializedResponseState<T2>>(subscriber => {
return observer
.pipe(
tap(() => {
subscriber.next({
loading: true,
error: null,
value: lastResponse,
})
}),
switchMap(performRequest)
)
.subscribe(
res => {
lastResponse = res
subscriber.next({
loading: false,
error: null,
value: res,
})
},
error => {
subscriber.error({
loading: false,
error,
value: lastResponse,
})
}
)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment