DispatchViewModel

abstract class DispatchViewModel : ViewModel

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

Link copied to clipboard
fun DispatchViewModel()

Functions

Link copied to clipboard
open fun addCloseable(@NonNull p0: Closeable)
Link copied to clipboard
fun clear()
Link copied to clipboard
open fun <T : Any> getTag(p0: String): T
Link copied to clipboard
open fun <T : Any> setTagIfAbsent(p0: String, p1: T): T

Properties

Link copied to clipboard
val viewModelScope: CoroutineScope

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

Sources

Link copied to clipboard