Android coroutine viewmodelscope cancel

Viewed 4480

I have seen a lot of examples that use a job as a way to cancel coroutines when viewmodel is destroyed.

class SetupViewModel : ViewModel() {

    private val completableJob = Job()
    private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)

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

The strange thing for me is no one seems to be using coroutineScope to do that. I think that should be easier and has less code. Any idea?

class SetupViewModel : ViewModel() {
    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    override fun onCleared() {
        super.onCleared()
        coroutineScope.cancel()
    }
}
2 Answers

Easy way you can use lifecycle-viewmodel-ktx and use viewModelScope already defined by library and you don't need override onCleared, read more here

I suppose your way of approach is actually correct. What is the exact problem?

Related