Khan
11/02/2019, 11:56 PMoctylFractal
11/02/2019, 11:57 PMAnastasia Finogenova
11/03/2019, 2:01 AMstreetsofboston
11/03/2019, 3:08 AMKhan
11/03/2019, 9:38 AMCoroutineScope.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 someonestreetsofboston
11/03/2019, 2:18 PMsuspend 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.Khan
11/03/2019, 2:27 PMstreetsofboston
11/03/2019, 4:30 PMviewModelScope.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)CoroutineScope
instance (not viewModelScope
, but one you created yourself, eg CoroutineScope(Job())
), then you are correct and you may have a leak.