...

/

Coroutine Builders: Using coroutineScope

Coroutine Builders: Using coroutineScope

Learn to use coroutineScope and get a summary of coroutine builders.

Imagine that in some repository function, we need to asynchronously load two resources—for example, user data and a list of articles. In this case, we want to return only those articles that the user should see. To call async, we need a scope, but we don’t want to pass it to a function. To create a scope out of a suspending function, we use the coroutineScope function.

Press + to interact
suspend fun getArticlesForUser(
userToken: String?,
): List<ArticleJson> = coroutineScope {
val articles = async { articleRepository.getArticles() }
val user = userService.getUser(userToken)
articles.await()
.filter { canSeeOnList(user, it) }
.map { toArticleJson(it) }
}

The suspending function coroutineScope creates a scope for its lambda expression. The function returns whatever the lambda expression ...