Last active
October 13, 2020 07:41
-
-
Save buhichan/bdb722b71266958d512ebf5a2b5db063 to your computer and use it in GitHub Desktop.
A rxjs operators that every web apps can use, but is not built-in
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 } from "rxjs" | |
import { switchMap, tap } from "rxjs/operators" | |
export type collectedResponse<T2> = { loading: boolean; error: null | Error; value: null | T2 } | |
export function collectResponse<T1, T2>(performRequest: (t1: T1) => SubscribableOrPromise<T2>) { | |
return (observer: Observable<T1>)=>{ | |
let lastResponse = null as null | T2 | |
return new Observable<collectedResponse<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