abbic
06/20/2024, 2:35 PMkevin.cianfarini
06/20/2024, 2:57 PMclass CoroutineAndroidViewModel(
private val scope = CoroutineScope(Job() + CoroutineName("…"))
) : ViewModel {
override fun onCleared() {
scope.cancel()
super.onCleared()
}
}
abbic
06/20/2024, 3:00 PMkevin.cianfarini
06/20/2024, 3:03 PMviewModelScope
is now discouraged by Google. You should use what I posted above, or you should add a CoroutineScope that implements the Closeable
interface to the viewmodel. https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycl[…]Main/kotlin/androidx/lifecycle/ViewModel.kt;l=138?q=ViewModelkevin.cianfarini
06/20/2024, 3:04 PMviewModelScope
tightly couples you to Dispatchers.Main.immediate
which causes issues, and as you’re experiencing, restricts your ability to universally add custom coroutine context elements to the scope.abbic
06/20/2024, 3:05 PMkevin.cianfarini
06/20/2024, 3:06 PMviewModelScope
Ian Lake
06/20/2024, 3:12 PMviewModelScope
is not discouraged - it was just changed to allow overriding it as it is now a constructor parameter: https://developer.android.com/jetpack/androidx/releases/lifecycle#2.8.0kevin.cianfarini
06/20/2024, 3:14 PMIan Lake
06/20/2024, 3:19 PMclass MyViewModel(
viewModelScope: CoroutineScope = Dispatchers.Main + SupervisorJob() + CoroutineName("yourName")
) : ViewModel(viewModelScope) {
// Use viewModelScope as before, without any code changes
}
kevin.cianfarini
06/20/2024, 3:19 PMkevin.cianfarini
06/20/2024, 3:20 PMIan Lake
06/20/2024, 3:22 PMIan Lake
06/20/2024, 3:23 PMkevin.cianfarini
06/20/2024, 3:25 PMIan Lake
06/20/2024, 3:38 PMkevin.cianfarini
06/20/2024, 3:55 PM