April 26, 2021 09:09 am GMT
Original Link: https://dev.to/fatehmohamed14/recursive-http-calls-the-rxjs-way-d61
Recursive Http Calls. The RXJS way
This article will show a quick example of achieving recursive http calls using RXJS for those who suffer from Promises.
Imagine that you want to collect all entries from an endpoint that only supports a paging API, means that you can't get all once. So the idea is to keep calling the Api by page till the last page which is our condition which our stop condition.
I'll use an Endpoint to fetch Artists
While next is truthy we proceed to the next call with the new page.
Let's move to the fun stuffs , To achieve that we will have a magic rxjs operator EXPAND.
import { from, EMPTY } from 'rxjs';import { expand, tap, switchMap } from 'rxjs/operators';let rows = []const firstUrl = 'https://api.happi.dev/v1/artists?page=1'const getArtists = (url: string) => from(fetch(url)).pipe( switchMap(response => response.json()))getArtists(firstUrl).pipe( tap(response => rows = rows.concat(response.result)), // on success we concat with the new coming rows expand((previousData) => previousData.next ? getArtists(previousData.next) : EMPTY; )).subscribe();
That's all , Goodbye
Original Link: https://dev.to/fatehmohamed14/recursive-http-calls-the-rxjs-way-d61
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To