Replies: 1 comment
-
|
Sandwich + coroutines handles both patterns cleanly. Sequential — B depends on A's result: suspend fun fetchUserWithProfile(userId: String): ApiResponse<UserProfile> =
apiService.getUser(userId) // ApiResponse<User>
.flatMap { user ->
apiService.getProfile(user.profileId) // ApiResponse<UserProfile>
}
Parallel — independent calls, combine results: suspend fun fetchDashboard(): ApiResponse<Dashboard> = coroutineScope {
val usersDeferred = async { apiService.getUsers() } // ApiResponse<List<User>>
val statsDeferred = async { apiService.getStats() } // ApiResponse<Stats>
val users = usersDeferred.await()
val stats = statsDeferred.await()
// zip combines two successful responses; propagates the first failure
users.zip(stats) { userList, statsData ->
Dashboard(users = userList, stats = statsData)
}
}Mixed — A parallel with B, but C depends on A: suspend fun fetchComplexData(): ApiResponse<Result> = coroutineScope {
// A and B start immediately in parallel
val aDeferred = async { apiService.getA() }
val bDeferred = async { apiService.getB() }
val responseA = aDeferred.await()
val responseB = bDeferred.await()
// C is sequential — it needs A's data
responseA
.flatMap { dataA -> apiService.getC(dataA.id) } // sequential on A
.zip(responseB) { c, b -> Result(c, b) } // merge with B
}Error handling across all patterns: fetchDashboard()
.onSuccess { dashboard -> render(dashboard) }
.onFailure { showError(it.message()) }
.onException { e -> logCrash(e) }Since |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
How to effectively combine sequential and parallel API calls, especially when one API sometimes depends on another?
Beta Was this translation helpful? Give feedback.
All reactions