Skip to main content

Top 5 Killer Use Cases for RxJS in NestJS

· 2 min read
Max Kaido
Architect

Here are top 5 killer use case examples for leveraging RxJS in NestJS to handle complex request chains efficiently:

1. Aggregating Data from Multiple APIs

  • Scenario: Your application needs to fetch user profile data from multiple APIs (e.g., basic info, purchase history, and recommendations).
  • Solution: Use forkJoin to execute parallel requests and combine their results into a single response.
return forkJoin({
basicInfo: this.httpService.get('/api/user/basic'),
purchaseHistory: this.httpService.get('/api/user/history'),
recommendations: this.httpService.get('/api/user/recommendations'),
}).pipe(map((results) => ({ ...results })));

2. Retry Logic for Fault Tolerance

  • Scenario: An external API might occasionally fail due to network issues. You need to retry the request before marking it as failed.
  • Solution: Use the retry operator to automatically retry the request a specified number of times.
return this.httpService.get('/api/data').pipe(
retry(3), // Retry up to 3 times
catchError((err) => throwError(() => new Error('Failed to fetch data'))),
);

3. Streaming Large Data in Chunks

  • Scenario: Download a large file or dataset in chunks and process each chunk as it arrives.
  • Solution: Use the mergeMap operator to process chunks sequentially or concurrently.
return from(chunkedUrls).pipe(
mergeMap((url) => this.httpService.get(url), 5), // Process up to 5 chunks concurrently
map((response) => processChunk(response.data)),
);

4. Handling Dependent Requests

  • Scenario: One request depends on the result of a previous request (e.g., fetch user token, then use it to retrieve user data).
  • Solution: Use the concatMap operator to handle dependent requests in a sequence.
return this.httpService.post('/auth/login', credentials).pipe(
map((response) => response.data.token),
concatMap((token) =>
this.httpService.get('/user/profile', {
headers: { Authorization: `Bearer ${token}` },
}),
),
map((response) => response.data),
);

5. Real-Time Updates with WebSockets

  • Scenario: Subscribe to a WebSocket feed for real-time data updates while simultaneously querying historical data from an API.
  • Solution: Use combineLatest to merge WebSocket updates with the historical data.
const historicalData$ = this.httpService
.get('/api/history')
.pipe(map((res) => res.data));
const liveUpdates$ = this.webSocketService.getUpdates();

return combineLatest([historicalData$, liveUpdates$]).pipe(
map(([history, liveUpdates]) => ({ history, liveUpdates })),
);

RxJS allows for reactive programming, making complex data flows and real-time updates manageable and efficient, especially when working with external APIs or streams of events.