5人参与 • 2025-08-19 • Android
这里系统梳理一下 android/kotlin 协程 的一些高级用法。会从 上下文管理、作用域控制、异常处理、性能优化、异步组合 等角度讲解,给你落地可用的示例。
在 android 中,协程最好绑定到 生命周期,避免内存泄漏。
class mainactivity : appcompatactivity() { // 生命周期感知协程作用域 private val scope = lifecyclescope override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) scope.launch { val data = fetchdata() updateui(data) } } }
private val customscope = coroutinescope(dispatchers.io + supervisorjob())
supervisorjob()
避免一个子协程失败影响其它子协程ondestroy()
或 oncleared()
时 customscope.cancel()
val result1 = async { fetchdata1() }.await() val result2 = async { fetchdata2() }.await() val finalresult = combine(result1, result2)
val deferred1 = async { fetchdata1() } val deferred2 = async { fetchdata2() } val result1 = deferred1.await() val result2 = deferred2.await()
val results = awaitall( async { fetchdata1() }, async { fetchdata2() }, async { fetchdata3() } )
scope.launch { try { val result = fetchdata() } catch (e: ioexception) { handleerror(e) } }
val handler = coroutineexceptionhandler { _, exception -> log.e("coroutine", "caught $exception") } scope.launch(handler) { val result = fetchdata() }
val supervisor = supervisorjob() val scope = coroutinescope(dispatchers.io + supervisor)
scope.launch(dispatchers.io) { val data = fetchdata() withcontext(dispatchers.main) { updateui(data) } }
launch
try { withtimeout(3000l) { fetchdata() } } catch (e: timeoutcancellationexception) { log.e("coroutine", "timeout") }
val job = scope.launch { fetchdata() } job.cancel() // 立即取消
isactive
:for (i in 1..1000) { if (!isactive) break dowork() }
val channel = channel<int>() scope.launch { for (i in 1..5) channel.send(i) channel.close() } scope.launch { for (i in channel) { println(i) } }
fun fetchnumbers(): flow<int> = flow { for (i in 1..5) { delay(100) emit(i) } } scope.launch { fetchnumbers() .map { it * 2 } .filter { it > 5 } .collect { println(it) } }
val flow1 = flow { emit(fetchdata1()) } val flow2 = flow { emit(fetchdata2()) } flow1.combine(flow2) { d1, d2 -> d1 + d2 } .collect { println(it) }
val deferred = async(start = coroutinestart.lazy) { fetchdata() } deferred.await() // 真正开始执行
supervisorjob()
避免一个子协程挂掉影响整个父协程到此这篇关于android协程的用法大全的文章就介绍到这了,更多相关android协程用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论