Android-CleanArchitecture-Kotlin
Android-CleanArchitecture-Kotlin copied to clipboard
Canceling UseCase job when ViewModel cleared
Do we need to cancel coroutine job in UseCase when ViewModel destroyed (onCleared())? As was done in previous implementation with Rx observables, which was disposed in Presenter.stop()
LiveData makes its observers inactive in onStop, so that they resubscribe in onStart.
@anegin, it is part of lifecycle in Activities, Fragments and services so it's not necessary destroy it.
Yes, you are right, LiveData won't send any event when receivers (Fragment, Activity) is not ready (is after onStop() state). But in my opinion it not a good practise to leave working thread alive when destroying Activity or Fragment.
Correct me if I'm wrong but when we start suspend function in worker thread in UseCase and does not handle any reference to pending work, we can not cancell it. The only communication from worker thread is via onResult callback.
One of possibilities is to handle Job reference in UseCase class, Job is returned by:
launch(UI) { onResult(job.await()) }
leave working thread alive when destroying Activity or Fragment.
That depends entirely on what your worker thread is doing, although if it is super-important then you might want to consider a foreground service while the task is running.
foreground service while the task is running
In my opinion Foreground Service should be used only for tasks which results is important in context of entire application, but ViewModel is tied to one specific View. But we are getting sidetrack, the problem is: Should we allow to worker thread running when view is completly destroyed?
@AppGrade-D You are right. Should actively cancel the worker thread when view is completly destroyed?