-
GlobalScope - 全局作用域,生命周期与应用程序一致
-
CustomScope - 自定义作用域,可以控制其生命周期
-
runBlocking - 阻塞当前线程直到协程完成
-
coroutineScope - 挂起函数,创建一个子作用域
-
supervisorScope - 子协程失败不会影响其他子协程
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import kotlinx.coroutines.*
import java.time.LocalTime
import java.time.format.DateTimeFormatter
// 定义不同类型的协程作用域
class CoroutineScopeDemo {
// 全局作用域 - 不推荐在生产代码中使用
fun globalScopeExample() {
GlobalScope.launch {
log("GlobalScope 启动的协程")
delay(2000)
log("GlobalScope 协程完成")
}
}
// 自定义作用域
private val customScope = CoroutineScope(Dispatchers.Default + CoroutineName("CustomScope"))
fun customScopeExample() {
customScope.launch {
log("CustomScope 启动的协程")
delay(1500)
log("CustomScope 协程完成")
}
}
// 使用 runBlocking - 会阻塞当前线程
fun runBlockingExample() {
log("runBlocking 开始")
runBlocking {
launch {
log("runBlocking 内部的协程")
delay(1000)
log("runBlocking 内部协程完成")
}
}
log("runBlocking 结束")
}
// 使用 coroutineScope - 挂起函数,不会阻塞线程
suspend fun coroutineScopeExample() {
log("coroutineScope 开始")
coroutineScope {
launch {
log("coroutineScope 内部的协程")
delay(1000)
log("coroutineScope 内部协程完成")
}
}
log("coroutineScope 结束")
}
// 使用 supervisorScope - 一个子协程的失败不会影响其他子协程
suspend fun supervisorScopeExample() {
log("supervisorScope 开始")
supervisorScope {
launch {
log("supervisorScope 第一个协程")
delay(1200)
log("supervisorScope 第一个协程完成")
}
launch {
log("supervisorScope 第二个协程")
delay(800)
log("supervisorScope 第二个协程完成")
}
}
log("supervisorScope 结束")
}
// 日志函数,带时间戳
private fun log(message: String) {
val time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
println("time \[{Thread.currentThread().name}] $message")
}
}
// Compose UI 界面
@Composable
fun App() {
val demo = remember { CoroutineScopeDemo() }
val coroutineScope = rememberCoroutineScope()
var logs by remember { mutableStateOf<List<String>>(emptyList()) }
fun addLog(message: String) {
val time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
logs = logs + "time - message"
if (logs.size > 10) logs = logs.drop(1)
}
MaterialTheme {
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Kotlin 协程作用域示例",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(bottom = 16.dp)
)
// 按钮行
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(bottom = 16.dp)
) {
Button(onClick = {
addLog("启动 GlobalScope 示例")
demo.globalScopeExample()
}) {
Text("GlobalScope")
}
Button(onClick = {
addLog("启动 CustomScope 示例")
demo.customScopeExample()
}) {
Text("CustomScope")
}
Button(onClick = {
addLog("启动 runBlocking 示例")
demo.runBlockingExample()
}) {
Text("runBlocking")
}
}
// 第二行按钮
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(bottom = 16.dp)
) {
Button(onClick = {
addLog("启动 coroutineScope 示例")
coroutineScope.launch {
demo.coroutineScopeExample()
}
}) {
Text("coroutineScope")
}
Button(onClick = {
addLog("启动 supervisorScope 示例")
coroutineScope.launch {
demo.supervisorScopeExample()
}
}) {
Text("supervisorScope")
}
}
// 显示日志
Card(
modifier = Modifier.fillMaxWidth().weight(1f)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
"运行日志:",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(bottom = 8.dp)
)
logs.forEach { log ->
Text(
text = log,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(vertical = 2.dp)
)
}
}
}
// 说明区域
Card(
modifier = Modifier.fillMaxWidth().padding(top = 16.dp)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
"协程作用域说明:",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(bottom = 8.dp)
)
Text(
"• GlobalScope: 全局作用域,生命周期与应用一致\n" +
"• CustomScope: 自定义作用域,可控制生命周期\n" +
"• runBlocking: 阻塞当前线程直到协程完成\n" +
"• coroutineScope: 挂起函数,创建一个子作用域\n" +
"• supervisorScope: 子协程失败不会影响其他子协程",
style = MaterialTheme.typography.bodySmall
)
}
}
}
}
}
// 运行程序
fun main() = application {
Window(onCloseRequest = ::exitApplication, title = "Kotlin 协程作用域示例") {
App()
}
}