android10 / android10/Android-CleanArchitecture-Kotlin

How to auto cancel UseCase job when the ViewModel is destroyed

未关闭
#118 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
Kotlin
星标
4.8k
派生
929
PR 合并指标
30 天内没有已合并 PR

描述

I want to auto cancel all UseCase request that is tied to the ViewModel.

For now: I have reigstered a callback for `ViewModel.onCleared()` event. So when the `onCleared()` is called, the callback will be invoked.

````
class BaseViewModel : ViewModel(){
internal var onClearedListener : () -> Unit ={}
override fun onCleared() {
super.onCleared()
onClearedListener.invoke()
}
}
````
For UseCase: I have defined two more functions, `cancelJob()` and `monitorViewModelLifecycle(vm: BaseViewModel)` and added another overloading function `invoke(vm: BaseViewModel,params: Params,onResult: (Either) -> Unit = {})`.

````
abstract class UseCase where Type : Any {
operator fun invoke(
vm: BaseViewModel,
params: Params,
onResult: (Either) -> Unit = {}
) {
monitorViewModelLifecycle(vm)
uiScope.launch { onResult(withContext(Dispatchers.IO) { run(params) }) }
}

//Cancel the current ongoing job
fun cancelJob(message: String = "Abort") {
uiScope.cancel(message)
}

/**
* Monitor the [BaseViewModel] lifecycle.
* The motto is to auto clear any ongoing job that is tied to the [BaseViewModel].
*
* @param vm, [BaseViewModel] instance
*/
fun monitorViewModelLifecycle(vm: BaseViewModel) {
vm.onClearedListener = {
cancelJob()
}
}
}
````

So, When the `ViewModel.onClearedListener` is invoked I'm cancelling the current Job.

Is there any better to way to acheive this?

贡献指南

这个仓库没有索引到贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。