Last active
April 15, 2021 07:58
-
-
Save buhichan/963a155d80eb4b1720c32ac0885b03cf to your computer and use it in GitHub Desktop.
rxjs-materialize-response.tsx
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
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