DispatchViewModel
Base class for ViewModels which will be using a viewModelScope.
The viewModelScope
instance is created automatically upon first access from the factory set in ViewModelScopeFactory.
The type of CoroutineScope created is configurable via ViewModelScopeFactory.set.
This must be an abstract class since nothing about the ViewModel.onCleared event is exposed.
viewModelScope
is automatically cancelled when onCleared()
is invoked.
Samples
import dispatch.android.viewmodel.DispatchViewModel
import dispatch.core.launchMain
import dispatch.internal.test.Sample5
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.isActive
fun main() {
//sampleStart
class SomeViewModel : DispatchViewModel() {
init {
// auto-created MainImmediateCoroutineScope which is auto-cancelled in onClear()
viewModelScope // ...
// it works as a normal CoroutineScope (because it is)
viewModelScope.launchMain { }
// this is the same CoroutineScope instance each time
viewModelScope.launchMain { }
}
override fun onClear() {
viewModelScope.isActive shouldBe false
}
}
//sampleEnd
}
Constructors
Functions
Properties
Link copied to clipboard
CoroutineScope instance for the DispatchViewModel. By default, it uses the Dispatchers.Main.immediate dispatcher