Skip to content

Instantly share code, notes, and snippets.

@disintegrator
Last active November 14, 2020 06:58
Show Gist options
  • Save disintegrator/3347892d058e896be0b7e50a3196d060 to your computer and use it in GitHub Desktop.
Save disintegrator/3347892d058e896be0b7e50a3196d060 to your computer and use it in GitHub Desktop.
RxJS + Axios
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'),
);
@anodynos
Copy link

Interesting experiment - comes 1st on google "axios rxjs".
But, you don't seem to be returning a subscription object with dispose or unsubscribe. Also I am confused with what line 9 does. Am I missing something?

@DavidNorena
Copy link

Checkout this It really worked for me !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment