前言
前面讲了Coroutine的实现原理。对协程有个初步的认识。
我们都知道协程是运行在CoroutineScope之下,而CoroutineScope下的协程也是有父子关系的。那么父协程取消的时候会取消所有子协程。
由此我们可以想到:CoroutineScope如果与Activity生命周期绑定,activity销毁了后CoroutineScope下的所有子协程就会随着activity一起消亡。这不正好符合我们的需求吗?activity结束后自动释放资源。
行动
常规写法
要与activity生命周期绑定。我们首先想到的是activity实现CoroutineScope,在onDestroy的时候调用job的cancel()来释放资源。这样虽好,但是要写一大堆代码阿,使用起来每次都得这么搞下,代码侵入性太强。
不过还是先看看代码把:
class MainActivity2 : MainActivity(), CoroutineScope {
val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = {Dispatchers.Main + job}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
优化写法
我们再看下经过我封装后的写法:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) = installCoroutineScope(savedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch {
repeat(100){
toast("ass")
}
}
}
}
啥?加一句installCoroutineScope(savedInstanceState)
代码就行了?协程也能直接在oncreate里launch了?对你没看错就是这么简单,无需关心activity结束后会取消协程。那么这行代码里做了什么呢?
1. LifecycleOwner
现在的AndroidAPI也是足够强大,提供了LifecycleOwner接口,activity都是它的子类,能够将生命周期拖过回调的方式抛出来,这样就给了我们解耦的可能,使得生命周期我们可以另外的处理。
2. Kotlin扩展函数
得益于Kotlin的扩展函数,我们能够另外的声明LifecycleOwner的扩展方法。我们可以扩展launch来让LifecycleOwner直接调用。
这二者一结合!installCoroutineScope(savedInstanceState)
就诞生了。
实现源码
具体就不详细说了,没几行,有什么问题欢迎留言,思想就是扩展installCoroutineScope,LifecycleOwner注册生命周期的回调,在回调中处理取消。
/**
* @Author : xialonghua
* @Date : Create in 2019/2/12
* @Description : a new file
*/
private class InternalCoroutineScope : LifecycleObserver, CoroutineScope{
val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(activity: LifecycleOwner) {
scopeMap[activity.toString()]?.job?.cancel()
scopeMap.remove(activity.toString())
activity.lifecycle.removeObserver(this)
}
}
private val scopeMap = HashMap<String, InternalCoroutineScope>()
/**
* 只需要在oncreate上添加即可<br>
* 绑定activity与协程Scope,尽量减少修改。</br>
* 注意:不要在onDestroy里启动协程</br>
* 使用方法:<br>
* ```
* override fun onCreate(savedInstanceState: Bundle?) = installCoroutineScope(savedInstanceState){
* super.onCreate(savedInstanceState)
* setContentView(R.layout.activity_main)
* }
* ```
*/
fun LifecycleOwner.installCoroutineScope(savedInstanceState: Bundle?, onCreate: (savedInstanceState: Bundle?) -> Unit){
if (scopeMap[this.toString()] != null){
return
}
val scope = InternalCoroutineScope()
scopeMap[this.toString()] = scope
lifecycle.addObserver(scope)
onCreate(savedInstanceState)
}
private fun LifecycleOwner.getCoroutineScope(): CoroutineScope{
return scopeMap[this.toString()]!!
}
fun LifecycleOwner.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job{
return getCoroutineScope().launch(context, start, block)
}
fun LifecycleOwner.launchOnIO(
context: CoroutineContext = EmptyCoroutineContext + Dispatchers.IO,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job{
return launch(context, start, block)
}
fun <T> LifecycleOwner.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>{
return getCoroutineScope().async(context, start, block)
}
fun <T> LifecycleOwner.asyncOnIO(
context: CoroutineContext = EmptyCoroutineContext + Dispatchers.IO,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>{
return async(context, start, block)
}
网友评论