android10 / android10/Android-CleanArchitecture-Kotlin

How to auto cancel UseCase job when the ViewModel is destroyed

Đang mở
#118 4 bình luận 0 reaction 0 người được giao Xem trên GitHub
Ngôn ngữ chính
Kotlin
Star
4.8k
Fork
929
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

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?

Hướng dẫn đóng góp

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.