AutomaticUpdateConditionsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/AutomaticUpdateConditionsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.library23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.services.scheduling.AutomaticUpdateGate7import eu.friedcutlet.yokan.services.scheduling.UpdateAdmission8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.CoroutineDispatcher10import kotlinx.coroutines.flow.*11import kotlinx.coroutines.launch12import kotlinx.coroutines.withContext1314data class AutomaticUpdateConditionsState(val checking: Boolean = false, val admission: UpdateAdmission? = null)1516class AutomaticUpdateConditionsViewModel(17 private val settings: SettingsStore,18 private val gate: AutomaticUpdateGate,19 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,20) : ViewModel() {21 private val _state = MutableStateFlow(AutomaticUpdateConditionsState())22 val state: StateFlow<AutomaticUpdateConditionsState> = _state.asStateFlow()23 private val refreshes = MutableStateFlow(0L)2425 init {26 viewModelScope.launch {27 gate.status.collect { admission -> _state.update { it.copy(admission = admission) } }28 }29 viewModelScope.launch {30 combine(settings.db.map { it.features.library.deviceConstraints to it.downloadOnlyOnWifi }.distinctUntilChanged(), refreshes) { _, _ -> Unit }31 .collectLatest {32 _state.update { it.copy(checking = true) }33 try { withContext(workDispatcher) { gate.check(settings.db.value, force = true) } }34 finally { _state.update { it.copy(checking = false) } }35 }36 }37 }3839 fun refresh() { refreshes.update { it + 1 } }40}41