viewModelScope

val viewModelScope: CoroutineScope

CoroutineScope instance for the DispatchViewModel. By default, it uses the Dispatchers.Main.immediate dispatcher

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.

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
}

Sources

Link copied to clipboard