AwaitAllScope

class AwaitAllScope(scope: CoroutineScope) : CoroutineScope

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()
)
}

Constructors

Link copied to clipboard
constructor(scope: CoroutineScope)

Properties

Link copied to clipboard

Functions

Link copied to clipboard
fun <T> async(context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T): Deferred<T>
Link copied to clipboard
suspend fun <A> CoroutineScope.awaitAll(block: suspend AwaitAllScope.() -> A): A