ViewModelTestHost.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt
1package eu.friedcutlet.yokan.ui23import androidx.lifecycle.ViewModel4import androidx.lifecycle.ViewModelStore5import kotlinx.coroutines.Dispatchers6import kotlinx.coroutines.ExperimentalCoroutinesApi7import kotlinx.coroutines.test.UnconfinedTestDispatcher8import kotlinx.coroutines.test.resetMain9import kotlinx.coroutines.test.setMain1011/** Installs an unconfined Main dispatcher and owns created view models; [close] clears them and restores Main. */12@OptIn(ExperimentalCoroutinesApi::class)13internal class ViewModelTestHost {14 val dispatcher = UnconfinedTestDispatcher()15 private val store = ViewModelStore()16 private var count = 01718 init { Dispatchers.setMain(dispatcher) }1920 fun <T : ViewModel> create(init: () -> T): T = init().also { store.put("vm${count++}", it) }2122 fun close() {23 store.clear()24 Dispatchers.resetMain()25 }26}27