Last active
November 14, 2020 06:58
-
-
Save disintegrator/3347892d058e896be0b7e50a3196d060 to your computer and use it in GitHub Desktop.
RxJS + Axios
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 axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; | |
import { Observable } from 'rxjs'; | |
const fromRequest = (request: AxiosRequestConfig) => | |
new Observable<AxiosResponse>( | |
(o) => { | |
const source = axios.CancelToken.source(); | |
o.add(() => source.cancel('Operation canceled by the user.')); | |
axios({ ...request, cancelToken: source.token }) | |
.then( | |
(response) => o.next(response), | |
(err) => axios.isCancel(err) ? console.log(err) : o.error(err) | |
); | |
} | |
); | |
const userIDs = ['1', '2', '3']; | |
const url = (id: string) => | |
`https://jsonplaceholder.typicode.com/posts?userId=${id}`; | |
const result = Observable.defer(() => { | |
return Observable | |
.from(userIDs) | |
.mergeMap(id => fromRequest({ url: url(id) }).flatMap(res => res.data)); | |
}); | |
// merge mapping userIDs with fromRequest's above can make up to 3 API requests | |
// since we take 12 values, the third request is cancelled. | |
result.take(12).subscribe( | |
x => console.log(x), | |
err => console.error('error:', err), | |
() => console.log('bye'), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting experiment - comes 1st on google "axios rxjs".
But, you don't seem to be returning a
subscription
object withdispose
orunsubscribe
. Also I am confused with what line 9 does. Am I missing something?