https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kevin.cianfarini

05/02/2019, 10:37 PM
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

louiscad

05/02/2019, 10:48 PM
@kevin.cianfarini Latest versions of it should use
SupervisorJob
under the hood. You can see all the latest versions on maven.google.com
k

kevin.cianfarini

05/02/2019, 10:50 PM
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

louiscad

05/02/2019, 10:51 PM
Don't forget to call
cancel()
from
onCleared()
3
k

kevin.cianfarini

05/03/2019, 1:02 AM
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

ghedeon

05/03/2019, 6:38 AM
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

louiscad

05/03/2019, 10:18 AM
Also, you can make your
onCleared()
override final, or annotate it with
@CallSuper
if you still need to override it in subclasses.
2 Views