Created
April 26, 2021 06:23
-
-
Save william-lohan/30c14d069a2a96c6e2dec3ac61376d16 to your computer and use it in GitHub Desktop.
wraps axios request in cancellable observable
This file contains 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, from } from 'rxjs'; | |
import { CancelToken, AxiosResponse } from "axios"; | |
/** | |
* @callback AxiosFn | |
* @param {CancelToken} cancelToken | |
* @returns {Promise<AxiosResponse>} | |
*/ | |
/** | |
* wraps axios request in cancellable observable | |
* @param {AxiosFn} axiosFn | |
* @returns {Observable<AxiosResponse>} | |
*/ | |
export function observableFromAxios(axiosFn) { | |
return new Observable(subscriber => { | |
const cancelToken = CancelToken.source(); | |
const promise = axiosFn(cancelToken); | |
from(promise).subscribe(subscriber); | |
return () => { | |
cancelToken.cancel("canceled by observable stream"); | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment