How to Use forkJoin in RxJS for Combining Observables
Use
forkJoin in RxJS to run multiple observables in parallel and wait until all complete, then get their last emitted values as an array or object. It is useful when you want to combine results from several async operations and proceed only after all finish.Syntax
The forkJoin function takes an array or object of observables and returns a new observable that emits a single value when all input observables complete. This emitted value contains the last emitted values from each input observable.
forkJoin([obs1, obs2, ...]): emits an array of last values.forkJoin({key1: obs1, key2: obs2}): emits an object with keys and last values.
typescript
import { forkJoin, of } from 'rxjs'; const obs1 = of('A'); const obs2 = of('B'); forkJoin([obs1, obs2]).subscribe(results => { console.log(results); // ['A', 'B'] }); forkJoin({first: obs1, second: obs2}).subscribe(results => { console.log(results); // { first: 'A', second: 'B' } });
Output
['A', 'B']
{ first: 'A', second: 'B' }
Example
This example shows how to use forkJoin to combine two HTTP requests in Angular. Both requests run in parallel, and the combined result is available only after both complete.
typescript
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { forkJoin } from 'rxjs'; @Component({ selector: 'app-user-posts', template: ` <h2>User and Posts</h2> <pre>{{ data | json }}</pre> ` }) export class UserPostsComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { const userRequest = this.http.get('https://jsonplaceholder.typicode.com/users/1'); const postsRequest = this.http.get('https://jsonplaceholder.typicode.com/posts?userId=1'); forkJoin({ user: userRequest, posts: postsRequest }).subscribe(result => { this.data = result; }); } }
Output
{ user: { id: 1, name: 'Leanne Graham', ... }, posts: [ { userId: 1, id: 1, title: '...', ... }, ... ] }
Common Pitfalls
Common mistakes when using forkJoin include:
- Expecting
forkJointo emit before all observables complete. It only emits once all complete. - Using observables that never complete (like
interval) will causeforkJointo never emit. - Not handling errors: if any observable errors,
forkJoinerrors immediately.
Always ensure input observables complete and handle errors properly.
typescript
import { forkJoin, interval, of } from 'rxjs'; import { take } from 'rxjs/operators'; // Wrong: interval never completes, forkJoin never emits forkJoin([interval(1000), of('done')]).subscribe(console.log); // Right: use take to complete interval forkJoin([interval(1000).pipe(take(3)), of('done')]).subscribe(console.log);
Output
Right example emits: [2, 'done'] after 3 seconds
Quick Reference
- forkJoin waits for all observables to complete.
- Emits a single combined value with last emitted values.
- Input can be an array or object of observables.
- Errors in any observable cause immediate error.
- Use with observables that complete (e.g., HTTP calls).
Key Takeaways
Use forkJoin to combine multiple observables and get their last emitted values after all complete.
forkJoin only emits once all input observables complete; it never emits if any never complete.
Input observables can be passed as an array or an object for flexible result shapes.
If any observable errors, forkJoin immediately errors and stops.
Ideal for combining HTTP requests or other finite async operations in Angular.