一篇文章带你彻底搞懂Kotlin的协程,移动app定制开发

异常捕获

协程里面的失败都可以通过异常捕获,来统一处理特殊情况

lifecycleScope.launch {

try {

val text=getText()

tvTest.text = text

} catch (e:Exception){

e.printStackTrace()

}

}

取消功能

下面执行了两个job,第一个是原始的,第二个是在1秒后取消第一个job,这会导致tvText的文本并不会改变

val job = lifecycleScope.launch {

try {

val text=getText()

tvTest.text = text

} catch (e:Exception){

e.printStackTrace()

}

}

lifecycleScope.launch {

delay(1000)

job.cancel()

}

设置超时

这个相当于系统封装了自动取消功能,对应函数withTimeout

lifecycleScope.launch {

try {

withTimeout(1000) {

val text = getText()

tvTest.text = text

}

} catch (e:Exception){

e.printStackTrace()

}

}

带返回值的Job

与launch类似的还有一个async方法,它会返回一个Deferred对象,属于Job的扩展类,Deferred可以获取返回的结果,具体使用如下

lifecycleScope.launch {

val one= async {

delay(1000)

return@async 1

}

val two= async {

delay(2000)

return@async 2

}

Log.i(“scope test”,(one.await()+two.await()).toString())

}

高级进阶


自定义CoroutineScope

先看CoroutineScope源码

public interface CoroutineScope {

public val coroutineContext: CoroutineContext

}

CoroutineScope中主要包含一个coroutineContext对象,我们要自定义只需实现coroutineContext的get方法

class TestScope() : CoroutineScope {

override val coroutineContext: CoroutineContext

get() = TODO(“Not yet implemented”)

}

要创建coroutineContext,得要先知道CoroutineContext是什么,我们再看CoroutineContext源码

/**

  • Persistent context for the coroutine. It is an indexed set of [Element] instances.

  • An indexed set is a mix between a set and a map.

  • Ever

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值