Repository navigation
Replies: 2 comments
|
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 |
|
One correction to the For “B is independent, C needs A,” you can make that dependency explicit: suspend fun load(): ApiResponse<Dashboard> = coroutineScope {
val b = async { api.getB() }
when (val a = api.getA()) {
is ApiResponse.Success -> {
val c = api.getC(a.data.id)
c.zip(b.await()) { cv, bv -> Dashboard(cv, bv) }
}
is ApiResponse.Failure.Error -> {
b.cancel()
a
}
is ApiResponse.Failure.Exception -> {
b.cancel()
a
}
}
}Here the service methods return See the actual |
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?
All reactions