min
07/12/2026, 12:48 PMViewModel instance has a viewModelScope: CoroutineScope. The docs say that i might want to consider adding my own CoroutineScope parameter:
class MyViewModel(private val coroutineScope: CoroutineScope): ViewModel() {
override fun onCleared() { this.coroutineScope.cancel() }
}
For better dependency injection during testing, and so on. Cancelling the scope might have unintended consequences though if it’s shared. What’s the best way to go about structuring concurrency in ViewModel instances? Take a context instead and construct a unique child scope for each instance?Ciaran Sloan
07/12/2026, 12:58 PMclass MyViewModel(coroutineScope: CoroutineScope): ViewModel(coroutineScope) {
fun doSomeWork() {
viewModelScope.launch {}
}
}min
07/13/2026, 8:15 AMonCleared to the superclass?
val scope = CoroutineScope(SupervisorJob())
val models = listOf(
MyViewModel(scope),
MyViewModel(scope),
MyViewModel(scope),
)
Clearing one still invalidates the scope for all three. How do I deal with this problem?Ciaran Sloan
07/13/2026, 8:23 AM