Junior — Middle
How can you determine your own context for ViewModelScope in Android?
sobes.tech AI
Answer from AI
In Android, ViewModelScope by default uses a context with the Dispatchers.Main dispatcher, which is convenient for UI work. To define a custom context for ViewModelScope, you can create your own CoroutineScope with the desired CoroutineContext and use it instead of the standard one.
For example, you can create an extension for ViewModel that uses a custom context:
class CustomViewModel : ViewModel() {
private val customScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun doWork() {
customScope.launch {
// Code runs here in Dispatchers.IO
}
}
override fun onCleared() {
super.onCleared()
customScope.cancel() // Cancel coroutines when ViewModel is destroyed
}
}
Thus, instead of viewModelScope.launch {}, use customScope.launch {} with the desired context.
If you need to change the context inside viewModelScope, you can use withContext:
viewModelScope.launch {
withContext(Dispatchers.IO) {
// Work in IO
}
}
But for full control over the context, it's better to create your own CoroutineScope in the ViewModel.