Can anyone explain to me the benefit of a `Corouti...
# coroutines
k
Can anyone explain to me the benefit of a
CoroutineScope
being provided in AndroidX LifeCycle as an extension
viewModelScope
versus just having viewmodel implement
CorutineScope
?
Nevermind, just found out that
viewModelScope
doesn't use a
SupervisorJob
under the hood. That's a non starter for me
l
@kevin.cianfarini Latest versions of it should use
SupervisorJob
under the hood. You can see all the latest versions on maven.google.com
k
I've actually stumbled upon a good way to do it which is to take as a param a CoroutineScope and implement that interface by delegatation. Should help with testing too
which seems very convenient for my use case
l
Don't forget to call
cancel()
from
onCleared()
3
k
Copy code
abstract class CoroutineViewModel(private val scope: CoroutineScope) : ViewModel(), CoroutineScope by scope {

    override fun onCleared() {
        super.onCleared()
        this.cancel(CancellationException("ViewModel called onCleared"))
    }
}
🙂
g
The benefit is composition over inheritance. If they change their mind about coroutines, the ViewModel will remain untouched. Also, coroutines is just another external library and it's a tall ask to depend on it.
2
l
Also, you can make your
onCleared()
override final, or annotate it with
@CallSuper
if you still need to override it in subclasses.