异常捕获
协程里面的失败都可以通过异常捕获,来统一处理特殊情况
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