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

Khan

11/02/2019, 11:56 PM
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

octylFractal

11/02/2019, 11:57 PM
if you use the view model scope it automatically cancels all jobs iirc
a

Anastasia Finogenova

11/03/2019, 2:01 AM
Kenzie is right the answer depends on the scope you use, but unless canceling or using viewModel scope it will
s

streetsofboston

11/03/2019, 3:08 AM
“How can we use CoroutineScopes in Kotlin?” by Anton Spaans https://link.medium.com/yEGedqvlg1
k

Khan

11/03/2019, 9:38 AM
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

streetsofboston

11/03/2019, 2:18 PM
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

Khan

11/03/2019, 2:27 PM
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

streetsofboston

11/03/2019, 4:30 PM
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.
5 Views