Skip to content

Instantly share code, notes, and snippets.

@se7en00
Forked from disintegrator/main.ts
Created August 5, 2020 14:00
Show Gist options
  • Select an option

  • Save se7en00/e046e18851e4a7cccfe52adc0cf1d151 to your computer and use it in GitHub Desktop.

Select an option

Save se7en00/e046e18851e4a7cccfe52adc0cf1d151 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'),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment