Kotlin 协程作用域

  1. GlobalScope - 全局作用域,生命周期与应用程序一致

  2. CustomScope - 自定义作用域,可以控制其生命周期

  3. runBlocking - 阻塞当前线程直到协程完成

  4. coroutineScope - 挂起函数,创建一个子作用域

  5. 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()

}

}

相关推荐
2301_768350231 天前
Vue第二期:组件及组件化和组件的生命周期
前端·javascript·vue.js
小周同学:1 天前
Vue项目中将界面转换为PDF并导出的实现方案
javascript·vue.js·pdf
ROO_KIE1 天前
[Java、C语言、Python、PHP、C#、C++]——深度剖析主流编程语言的核心特性与应用场景
kotlin
alexhilton1 天前
Kotlin互斥锁(Mutex):协程的线程安全守护神
android·kotlin·android jetpack
90后的晨仔1 天前
Vue 3 组合式函数(Composables)全面解析:从原理到实战
前端·vue.js
90后的晨仔1 天前
Vue 3 中 Provide / Inject 在异步时不起作用原因分析(二)?
前端·vue.js
90后的晨仔1 天前
Vue 3 中 Provide / Inject 在异步时不起作用原因分析(一)?
前端·vue.js
90后的晨仔1 天前
Vue 异步组件(defineAsyncComponent)全指南:写给新手的小白实战笔记
前端·vue.js
木易 士心1 天前
Vue 与 React 深度对比:底层原理、开发体验与实际性能
前端·javascript·vue.js
Lucky GGBond1 天前
Vue + Spring Boot 实现 Excel 导出实例
vue.js·spring boot·excel