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<Failure, Type>) -> Unit = {}).
abstract class UseCase<out Type, in Params> where Type : Any {
operator fun invoke(
vm: BaseViewModel,
params: Params,
onResult: (Either<Failure, Type>) -> 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?
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 theonCleared()is called, the callback will be invoked.For UseCase: I have defined two more functions,
cancelJob()andmonitorViewModelLifecycle(vm: BaseViewModel)and added another overloading functioninvoke(vm: BaseViewModel,params: Params,onResult: (Either<Failure, Type>) -> Unit = {}).So, When the
ViewModel.onClearedListeneris invoked I'm cancelling the current Job.Is there any better to way to acheive this?