|
| 1 | +# forkJoin |
| 2 | + |
| 3 | +`forkJoin()` is used when you have a group of Observables (often representing asynchronous operations like API calls) and you want to wait until **all** of them have **completed** before you get the results. |
| 4 | + |
| 5 | +Think of it like starting several independent tasks (e.g., downloading multiple files, making several API requests). `forkJoin` waits patiently until every single one of those tasks signals "I'm finished!". Once the last task completes, `forkJoin` emits a _single_ value, which is an array containing the _very last value_ emitted by each of the input Observables, in the same order you provided them. |
| 6 | + |
| 7 | +## Key Characteristics |
| 8 | + |
| 9 | +1. **Waits for Completion:** It doesn't emit anything until _every_ input Observable finishes (completes). |
| 10 | +2. **Parallel Execution:** It subscribes to all input Observables immediately, allowing them to run in parallel. |
| 11 | +3. **Single Emission:** It emits only _one_ value (or an error). |
| 12 | +4. **Array of Last Values:** The emitted value is an array containing the _last_ value from each input Observable. |
| 13 | +5. **Error Behavior:** If _any_ of the input Observables error out, `forkJoin` immediately errors out as well. It will _not_ wait for the other Observables to complete and will _not_ emit the array of results. |
| 14 | + |
| 15 | +## Real-World Analogy |
| 16 | + |
| 17 | +Imagine you're ordering dinner from three different places via delivery apps: |
| 18 | + |
| 19 | +- App 1: Pizza |
| 20 | +- App 2: Salad |
| 21 | +- App 3: Drinks |
| 22 | + |
| 23 | +You want to start eating only when _everything_ has arrived. `forkJoin` is like waiting by the door. It doesn't matter if the pizza arrives first, or the drinks. You only care about the moment the _last_ delivery person arrives. At that exact moment, `forkJoin` gives you the complete meal: `[Pizza, Salad, Drinks]`. |
| 24 | + |
| 25 | +However, if any single order fails (e.g., the pizza place cancels), `forkJoin` immediately tells you there's a problem ("Error: Pizza order cancelled!") and you don't get the combined results. |
| 26 | + |
| 27 | +**Handling Errors within `forkJoin`:** |
| 28 | + |
| 29 | +Because `forkJoin` fails completely if any input stream errors, you often want to handle potential errors _within_ each input stream _before_ they reach `forkJoin`. You can use the `catchError` operator for this, typically returning a fallback value (like `null`, `undefined`, or an empty object/array) so that the stream still _completes_ successfully. |
| 30 | + |
| 31 | +```typescript |
| 32 | +import { forkJoin, of, timer, throwError } from "rxjs"; |
| 33 | +import { delay, catchError } from "rxjs/operators"; |
| 34 | + |
| 35 | +const successful$ = of("Success Data").pipe(delay(500)); |
| 36 | + |
| 37 | +// Simulate an API call that fails |
| 38 | +const failing$ = timer(1500).pipe( |
| 39 | + delay(100), // Add small delay just for simulation |
| 40 | + map(() => { |
| 41 | + throw new Error("Network Error"); |
| 42 | + }) // Simulate error |
| 43 | +); |
| 44 | + |
| 45 | +// --- Without error handling inside --- |
| 46 | +// forkJoin([successful$, failing$]).subscribe({ |
| 47 | +// next: results => console.log('This will not run'), |
| 48 | +// error: err => console.error('forkJoin failed because one stream errored:', err.message) // This will run |
| 49 | +// }); |
| 50 | + |
| 51 | +// --- With error handling inside the failing stream --- |
| 52 | +console.log("\nStarting forkJoin with internal error handling..."); |
| 53 | +const failingHandled$ = failing$.pipe( |
| 54 | + catchError((error) => { |
| 55 | + console.warn(`Caught error in stream: ${error.message}. Returning null.`); |
| 56 | + // Return an Observable that emits a fallback value and COMPLETES |
| 57 | + return of(null); |
| 58 | + }) |
| 59 | +); |
| 60 | + |
| 61 | +forkJoin([successful$, failingHandled$]).subscribe({ |
| 62 | + next: (results) => { |
| 63 | + // This will run after ~1.6 seconds |
| 64 | + console.log("forkJoin completed with results:", results); // results: ['Success Data', null] |
| 65 | + }, |
| 66 | + error: (err) => { |
| 67 | + console.error("This should not run if errors are handled internally:", err); |
| 68 | + }, |
| 69 | +}); |
| 70 | + |
| 71 | +/* |
| 72 | +Expected Output: |
| 73 | +Starting forkJoin with internal error handling... |
| 74 | +(after ~1.6 seconds) |
| 75 | +Caught error in stream: Network Error. Returning null. |
| 76 | +forkJoin completed with results: [ 'Success Data', null ] |
| 77 | +*/ |
| 78 | +``` |
| 79 | + |
| 80 | +## Angular Example: Loading Initial Page Data |
| 81 | + |
| 82 | +`forkJoin` is perfect for loading all the essential data a component needs before displaying anything. |
| 83 | + |
| 84 | +```typescript |
| 85 | +import { Component, OnInit } from "@angular/core"; |
| 86 | +import { HttpClient } from "@angular/common/http"; |
| 87 | +import { forkJoin, of } from "rxjs"; |
| 88 | +import { catchError } from "rxjs/operators"; |
| 89 | + |
| 90 | +interface UserProfile { |
| 91 | + name: string; |
| 92 | + email: string; |
| 93 | +} |
| 94 | +interface UserPreferences { |
| 95 | + theme: string; |
| 96 | + language: string; |
| 97 | +} |
| 98 | +interface InitialNotifications { |
| 99 | + count: number; |
| 100 | + messages: string[]; |
| 101 | +} |
| 102 | + |
| 103 | +@Component({ |
| 104 | + selector: "app-profile-page", |
| 105 | + template: ` |
| 106 | + <div *ngIf="!isLoading && !errorMsg"> |
| 107 | + <h2>Profile: {{ profile?.name }}</h2> |
| 108 | + <p>Email: {{ profile?.email }}</p> |
| 109 | + <p>Theme: {{ preferences?.theme }}</p> |
| 110 | + <p>Notifications: {{ notifications?.count }}</p> |
| 111 | + </div> |
| 112 | + <div *ngIf="isLoading">Loading profile data...</div> |
| 113 | + <div *ngIf="errorMsg" style="color: red;">{{ errorMsg }}</div> |
| 114 | + `, |
| 115 | +}) |
| 116 | +export class ProfilePageComponent implements OnInit { |
| 117 | + isLoading = true; |
| 118 | + errorMsg: string | null = null; |
| 119 | + |
| 120 | + profile: UserProfile | null = null; |
| 121 | + preferences: UserPreferences | null = null; |
| 122 | + notifications: InitialNotifications | null = null; |
| 123 | + |
| 124 | + constructor(private http: HttpClient) {} |
| 125 | + |
| 126 | + ngOnInit() { |
| 127 | + this.loadData(); |
| 128 | + } |
| 129 | + |
| 130 | + loadData() { |
| 131 | + this.isLoading = true; |
| 132 | + this.errorMsg = null; |
| 133 | + |
| 134 | + // Define the API calls - HttpClient observables complete automatically |
| 135 | + const profile$ = this.http.get<UserProfile>("/api/profile").pipe( |
| 136 | + catchError((err) => { |
| 137 | + console.error("Failed to load Profile", err); |
| 138 | + // Return fallback and let forkJoin continue |
| 139 | + return of(null); |
| 140 | + }) |
| 141 | + ); |
| 142 | + |
| 143 | + const preferences$ = this.http |
| 144 | + .get<UserPreferences>("/api/preferences") |
| 145 | + .pipe( |
| 146 | + catchError((err) => { |
| 147 | + console.error("Failed to load Preferences", err); |
| 148 | + // Return fallback and let forkJoin continue |
| 149 | + return of(null); |
| 150 | + }) |
| 151 | + ); |
| 152 | + |
| 153 | + const notifications$ = this.http |
| 154 | + .get<InitialNotifications>("/api/notifications") |
| 155 | + .pipe( |
| 156 | + catchError((err) => { |
| 157 | + console.error("Failed to load Notifications", err); |
| 158 | + // Return fallback and let forkJoin continue |
| 159 | + return of({ count: 0, messages: [] }); // Example fallback |
| 160 | + }) |
| 161 | + ); |
| 162 | + |
| 163 | + // Use forkJoin to wait for all requests |
| 164 | + forkJoin([profile$, preferences$, notifications$]).subscribe( |
| 165 | + ([profileResult, preferencesResult, notificationsResult]) => { |
| 166 | + // This block runs when all API calls have completed (successfully or with handled errors) |
| 167 | + console.log("All data received:", { |
| 168 | + profileResult, |
| 169 | + preferencesResult, |
| 170 | + notificationsResult, |
| 171 | + }); |
| 172 | + |
| 173 | + // Check if essential data is missing |
| 174 | + if (!profileResult || !preferencesResult) { |
| 175 | + this.errorMsg = |
| 176 | + "Could not load essential profile data. Please try again later."; |
| 177 | + } else { |
| 178 | + this.profile = profileResult; |
| 179 | + this.preferences = preferencesResult; |
| 180 | + this.notifications = notificationsResult; // Notifications might be optional or have a fallback |
| 181 | + } |
| 182 | + |
| 183 | + this.isLoading = false; |
| 184 | + }, |
| 185 | + (err) => { |
| 186 | + // This error handler is less likely to be hit if catchError is used inside, |
| 187 | + // but good practice to have for unexpected issues. |
| 188 | + console.error("Unexpected error in forkJoin:", err); |
| 189 | + this.errorMsg = "An unexpected error occurred while loading data."; |
| 190 | + this.isLoading = false; |
| 191 | + } |
| 192 | + ); |
| 193 | + } |
| 194 | +} |
| 195 | +``` |
| 196 | + |
| 197 | +In this example, the component makes three API calls. The `forkJoin` ensures that the loading indicator stays active until _all three_ requests are finished. By using `catchError` inside each request, we prevent one failed request from stopping the others, and we can handle missing data appropriately in the `next` callback of `forkJoin`. |
| 198 | + |
| 199 | +## Summary |
| 200 | + |
| 201 | +use `forkJoin` when you need to run several asynchronous operations (that eventually complete) in parallel and only want to proceed once you have the final result from _all_ of them. Remember its strict error handling behavior and use `catchError` internally if necessary. |
0 commit comments