// 通常在 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!")
}