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

}

}

相关推荐
小林rush21 小时前
深入 Vue3 编译原理:实现一个mini模板编译器
前端·vue.js·前端框架
小孔龙2 天前
04.Kotlin Serialization - 序列化器的使用
kotlin·json
我是日安2 天前
从零到一打造 Vue3 响应式系统 Day 11 - Effect:Link 节点的复用实现
前端·vue.js
小孔龙2 天前
05.Kotlin Serialization - 多态序列化入门
kotlin·json
XDMrWu2 天前
Compose 智能重组:编译器视角下的黑科技
android·kotlin
徐小夕2 天前
支持1000+用户同时在线的AI多人协同文档JitWord,深度剖析
前端·vue.js·算法
离子守恒2 天前
Vue 核心——响应式系统
vue.js
前行的小黑炭2 天前
Android :Compose如何监听生命周期?NavHostController和我们传统的Activity的任务栈有什么不同?
android·kotlin·app
前行的小黑炭2 天前
Android 关于状态栏的内容:开启沉浸式页面内容被状态栏遮盖;状态栏暗亮色设置;
android·kotlin·app
passer9813 天前
基于Vue的场景解决
前端·vue.js