🚀 launch · async · runBlocking

协程构建器 Compose 实战
⚡ 在 Kotlin 协程中,launch、async、runBlocking 是三个最核心的构建器。
它们决定了协程的生命周期、返回值以及调度方式。在 Jetpack Compose 中正确使用它们,是构建流畅 UI 的关键。
构建器 返回值 协程作用域 异常传播 Compose 典型场景
launch Job (无结果) CoroutineScope 自动抛出 (可取消) 触发一次性事件、更新 State、动画
async Deferred<T> (可 await) CoroutineScope 在 await 时抛出 并行网络请求、异步计算结果
runBlocking T (阻塞当前线程) 全局 (阻塞) 直接抛出 测试 / 启动入口 (非 Compose UI 线程)
launch · 即发即忘
async · 期待结果
runBlocking · 阻塞桥接

📌 launch — 在 Compose 中启动协程

// 通常在 rememberCoroutineScope 中使用
@Composable
fun LaunchExample() {
    val scope = rememberCoroutineScope()
    var text by remember { mutableStateOf("点击加载") }

    Button(onClick = {
        scope.launch {
            // 挂起函数,不阻塞UI
            val data = fetchData()  
            text = data
        }
    }) {
        Text(text)
    }
}

📌 async — 并发获取并组合结果

suspend fun loadUserAndPosts(): UserWithPosts {
    coroutineScope {
        val userDeferred = async { fetchUser() }
        val postsDeferred = async { fetchPosts() }
        // 同时等待两个结果
        UserWithPosts(userDeferred.await(), postsDeferred.await())
    }
}

📌 runBlocking — 测试 / 非协程环境桥接

// 在单元测试中常用,但不要在 Compose UI 线程使用
@Test
fun testCoroutine() = runBlocking {
    val result = fetchData()
    assertEquals("expected", result)
}

// 或者用于 main 函数入口
fun main() = runBlocking {
    println("Hello from coroutine!")
}
🏗️ 协程构建器 · Compose 架构图 launch Job · 无返回值 UI 事件 · 状态更新 rememberCoroutineScope async Deferred<T> · await 并行网络 / 数据库 async + await 组合 runBlocking 阻塞当前线程 测试 / 入口函数 ⚠️ Compose中避免使用 非阻塞 阻塞桥接 ⬆️ 在 Compose 中优先使用 launch / async,runBlocking 仅用于测试或协程入口

🎯 使用区别 · 一句话记忆

  • L launch — 点火起飞,不回头(无返回值,适合UI事件)
  • A async — 异步任务,期待结果(Deferred,可并发)
  • R runBlocking — 阻塞线程,用于测试/入口(Compose UI 中慎用)