Every `ViewModel` instance has a `viewModelScope: ...
# android
m
Every
ViewModel
instance has a
viewModelScope: CoroutineScope
. The docs say that i might want to consider adding my own
CoroutineScope
parameter:
Copy code
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?
c
Pass the coroutineScope into the ViewModel abstract class and the cancellation will be handled for you. You can then continue to use viewModelScope as it will be set as the provided scope:
Copy code
class MyViewModel(coroutineScope: CoroutineScope): ViewModel(coroutineScope) {
    fun doSomeWork() {
        viewModelScope.launch {}
    }
}
m
@Ciaran Sloan Wouldn’t that just delegate the cancellation on
onCleared
to the superclass?
Copy code
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?
c
Creating multiple instances of a view model is not the same thing as sharing a view model. If you're creating multiple instances you should also create a scope for that instance. Not attempt to share a single scope across multiple instances of the VM