'Am I canceling coroutines correctly

I have my view model as such

class StorageValidationViewModel: ViewModel(), CoroutineScope {

    //Coroutines
    private val _job = SupervisorJob()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + _job

    override fun onCleared() {
        super.onCleared()
        coroutineContext.cancel()
    }
    ......
}

I have some methods that make a network call via Retrofit that start a coroutine

fun getStorageLocations(){
        launch {
            var locations:List<StorageLocationData>? = null
            try {
                locations = _storageLocationRepository.getAllStorageLocations()
            }catch (e:IOException){
                e.printStackTrace()
            }

            storageLocationsLiveData.postValue(locations)
        }
    }

Everything works fine but I have a feeling that I am not canceling the coroutines correctly when the ViewModel is getting cleared because I dont actually use coroutineContext anywhere thus creating a memory leak

should I be doing

launch(coroutineContext){
    //API call?
}

or is what I am doing fine? I just want to make sure I am not creating memory leaks with what I am doing



Solution 1:[1]

You don't create memory leaks with your implementation. coroutineContext: CoroutineContext is a property which must be implemented when inheriting from CoroutineScope. When launching a coroutine using launch coroutine builder it uses overridden coroutineContext context, so you don't need to pass it explicitly to the launch() builder.

There is more straightforward way to use coroutines in a ViewModel. viewModelScope property can be used to launch a coroutine without inheriting from CoroutineScope:

class MyViewModel: ViewModel() {
    init {
        viewModelScope.launch {
            // Coroutine that will be canceled when the ViewModel is cleared.
        }
    }
}

And no need to cancel the job explicitly in onCleared() method.

For viewModelScope, use androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0 or higher.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BigSt