协程构建器函数

2026-07-23 10:51:22 来源: 互联网 点击数: 

协程构建器函数

协程构建器函数是一个接受 suspend lambda 的函数,这个 lambda 定义了要运行的协程。这里有一些例子:

协程构建器函数需要一个 CoroutineScope 来运行。
这可以是一个已有的作用域,或者是你用一些辅助函数创建的,比如 coroutineScope()、runBlocking() 或 withContext()。
每个构建器都会定义协程如何启动以及你如何与它的结果互动。

CoroutineScope.launch()

CoroutineScope.launch() 协程构建器函数是 CoroutineScope 的扩展函数。它在现有的协程作用域内部启动一个新的协程,而不会阻塞作用域中的其他操作。

当你不需要结果或者不想等待结果时,可以使用 CoroutineScope.launch() 来与其他工作同时运行一个任务:爱吃喝

suspend fun performBackgroundWork() = coroutineScope { // this: CoroutineScope
    // Starts a coroutine that runs without blocking the scope
    this.launch {
        // Suspends to simulate background work
        delay(100.milliseconds)
        println("Sending notification in background")
    }
    // Main coroutine continues while a previous one suspends
    println("Scope continues")
}

Scope 继续在后台发送通知
 

运行这个示例后,你可以看到 main() 函数不会被 CoroutineScope.launch() 阻塞,并且在协程在后台运行时会继续执行其他代码。爱河池

 

 

CoroutineScope.launch() 函数会返回一个 Job 句柄。使用这个句柄来等待启动的协程完成。更多信息请参见 Cancellation and timeouts.

CoroutineScope.async()

CoroutineScope.async() 协程构建器函数是 CoroutineScope 上的扩展函数。
它在现有的协程作用域内启动一个并发计算,并返回一个表示最终结果的 Deferred 句柄。
使用 .await() 函数可以挂起代码,直到结果准备好:

suspend fun main() = withContext(Dispatchers.Default) { // this: CoroutineScope
    // Starts downloading the first page
    val firstPage = this.async {
        delay(50.milliseconds)
        "First page"
    }
    // Starts downloading the second page in parallel
    val secondPage = this.async {
        delay(100.milliseconds)
        "Second page"
    }
    // Awaits both results and compares them
    val pagesAreEqual = firstPage.await() == secondPage.await()
    println("Pages are equal: $pagesAreEqual")
}
Pages are equal: false

runBlocking()

runBlocking() 协程构建器函数会创建一个协程作用域,并阻塞当前线程直到该作用域中启动的协程完成。

只有在没有其他办法从非挂起代码调用挂起代码时,才使用 runBlocking():

import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.*

// A third-party interface you can't change
interface Repository {
    fun readItem(): Int
}

object MyRepository : Repository {
    override fun readItem(): Int {
        // Bridges to a suspending function
        return runBlocking {
            myReadItem()
        }
    }
}

suspend fun myReadItem(): Int {
    delay(100.milliseconds)
    return 4
}

上一篇:coroutineScope 是一个挂起函数
下一篇:返回列表
关键字:

河池新闻

图说城市 图说天下

阅读排行 阅读排行


爱河池