Why and when do we actually need to implement CoroutineScope
in a ViewModel
. Inside ViewModel you can use viewModelScope
when you want to tied your Coroutine to the ViewModel thus when onCleared
gets called all running coroutines will be cancelled automatically. When you implement CoroutineScope
you can directly call launch
, what scope does it use? I am guessing it uses the one provided at override val coroutineContext: CoroutineContext
. Does implementing CoroutineScope
in a ViewModel means you want to handle the cancellation of coroutine by yourself?
It is not very commonly necessary. The purpose of creating a CoroutineScope is to manage the lifecycle of multiple coroutines. If for some reason you have some coroutines you want to launch in a ViewModel, and you want to possibly cancel all of them at some time other than when the ViewModel is destroyed, then it would be handy to have a separate CoroutineScope from viewModelScope
to launch those coroutines from. It would be up to you to cancel this scope at the appropriate time to avoid coroutines living longer than you want them to and leaking memory.
If your ViewModel itself implements CoroutineScope and you directly call launch
, it is using itself as the scope that launches the coroutine. But it's still up to you to cancel it at the appropriate time. Otherwise, the ViewModel could be in destroyed state, but still have some coroutines running in its scope and hanging onto memory and preventing the ViewModel from being freed to the GC.