如何正确的在 Android 上使用协程?( 三 )


所以 livedata-ktx 的使用是有一定限制的 。对于需要用户主动刷新的场景 , 就无法满足了 。在一次完整的生命周期内 , 一旦成功执行完成一次 , 就没有办法再触发了 。 这句话不知道对不对 , 我个人是这么理解的 。因此 , 还是 viewmodel-ktx 的适用性更广 , 可控性也更好 。
LifecycleScope
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha03"lifecycle-runtime-ktx 给每个 LifeCycle 对象通过扩展属性定义了协程作用域 lifecycleScope。你可以通过 lifecycle.coroutineScope 或者 lifecycleOwner.lifecycleScope 进行访问 。示例代码如下:
fun getMessageByLifeCycle(lifecycleOwner: LifecycleOwner) { lifecycleOwner.lifecycleScope.launch { val deferred = async(Dispatchers.IO) { getMessage("LifeCycle Ktx") } mMessage.value = https://www.isolves.com/it/cxkf/ydd/Android/2019-10-22/deferred.await() }}当 LifeCycle 回调 onDestroy() 时 , 协程作用域 lifecycleScope 会自动取消 。在 Activity/Fragment 等生命周期组件中我们可以很方便的使用 , 但是在 MVVM 中又不会过多的在 View 层进行逻辑处理 , viewModelScope 基本就可以满足 ViewModel 中的需求了 , lifecycleScope 也显得有点那么食之无味 。但是他有一个特殊的用法:
suspend fun <T> Lifecycle.whenCreated()suspend fun <T> Lifecycle.whenStarted()suspend fun <T> Lifecycle.whenResumed()suspend fun <T> LifecycleOwner.whenCreated()suspend fun <T> LifecycleOwner.whenStarted()suspend fun <T> LifecycleOwner.whenResumed()可以指定至少在特定的生命周期之后再执行挂起函数 , 可以进一步减轻 View 层的负担 。
总结

以上简单的介绍了在 Android 中合理使用协程的一些方案 , 示例代码已上传至 https://github.com/lulululbj/CoroutineDemo 。关于 MVVM + 协程 的实战项目 , 可以看看我的开源项目 https://github.com/lulululbj/wanandroid , 同时也期待你宝贵的意见 。

【如何正确的在 Android 上使用协程?】


推荐阅读