Skip to content

Instantly share code, notes, and snippets.

@william-lohan
Created April 26, 2021 06:23
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 william-lohan/30c14d069a2a96c6e2dec3ac61376d16 to your computer and use it in GitHub Desktop.
Save william-lohan/30c14d069a2a96c6e2dec3ac61376d16 to your computer and use it in GitHub Desktop.
wraps axios request in cancellable observable
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