AwaitAllScope
Within an AwaitAllScope, any call to kotlinx.coroutines.Deferred.await causes all the other Deferred in the same block to be awaited too. That way you can get more concurrency without having to sacrifice readability.
suspend fun loadUserInfo(id: UserId): UserInfo = await {
val name = async { loadUserFromDb(id) }
val avatar = async { loadAvatar(id) }
UserInfo(
name.await(), // <- at this point every 'async' is 'await'ed
avatar.await() // <- so when you reach this 'await', the value is already there
)
}
suspend fun loadUserInfoWithoutAwait(id: UserId): UserInfo {
val name = async { loadUserFromDb(id) }
val avatar = async { loadAvatar(id) }
awaitAll(name, avatar) // <- this is required otherwise
return UserInfo(
name.await(),
avatar.await()
)
}
Content copied to clipboard