-
-
Save se7en00/e046e18851e4a7cccfe52adc0cf1d151 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