If i start a coroutine with CoroutineScope inside ...
# coroutines
k
If i start a coroutine with CoroutineScope inside ViewModel (which is doing some db operation but this operation doesn’t return anything. So coroutine starts performs db operation and completes). During this operation if my viewmodel onCleared() is called but i don’t cancel coroutine will my viewmodel leak?
o
if you use the view model scope it automatically cancels all jobs iirc
a
Kenzie is right the answer depends on the scope you use, but unless canceling or using viewModel scope it will
s
“How can we use CoroutineScopes in Kotlin?” by Anton Spaans https://link.medium.com/yEGedqvlg1
k
Thanks for the answers. I know about viewmodel scope. But i just wanna make sure what i have asked above.
Copy code
CoroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>){
//Something...
}
If i start coroutine like this in viewmodel If viewmodel is cleared but coroutine is not cancelled, will my viewmodel leak? If it’s not finishing the job before the ViewModel gets cleared then the ViewModel can’t be garbage collected and a leak will occur. Got this statement from someone
s
When a CoroutineScope ends (canceled, finished normally or through an exception), all it's 'child' Coroutines will be canceled. There is no need to keep track of all the `Job`s and `Deferred`s and cancel them individually.
Note that a Coroutine can only be properly canceled when it is suspending (i.e. a
suspend fun
was called and is currently suspending). A Coroutine that is still actively running or blocking won't get magically canceled. Also, you can call
isActive
in your normal/non-suspending parts of the code in your Coroutine to exit tight loops or skip long-lasting blocking parts of your code.
k
Yes i understand that. But i am asking about this speciifc case, where i don't have any child. Its only one coroutine which is created from viewmodel. If viewmodel on cleared is called and we don't cancel coroutine, will it cause a leak.
s
You create Coroutine by calling
viewModelScope.launch
or
viewModelScope.async
. When the
viewModelScope
gets canceled in the
onCleared
of the ViewModel, all your Coroutines(s) launched that way will be canceled as well and nothing leaks (unless your Coroutines are blocking and never suspending)
If you use another
CoroutineScope
instance (not
viewModelScope
, but one you created yourself, eg
CoroutineScope(Job())
), then you are correct and you may have a leak.