DEV Community

Cover image for Recursive Http Calls. The RXJS way 😎
Fateh Mohamed 🐒
Fateh Mohamed 🐒

Posted on

6 2

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 rows at once. So the idea is to keep calling the Api by page till the last page which is our stop condition.

I'll use an Endpoint to fetch Artists

image

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();


Enter fullscreen mode Exit fullscreen mode

Alt Text

That's all πŸ₯±, Goodbye πŸ–πŸ»

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
larbibaraka profile image
Baraka Larbi β€’

awesome bro thank you

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay