Privacy-Period-Tracker/app/src/main/kotlin/dev/privacyllc/period/navigation/RootViewModel.kt

40 lines
1.5 KiB
Kotlin

package dev.privacyllc.period.navigation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.privacyllc.period.core.datastore.UserPreferencesRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
enum class RootState { Loading, Onboarding, Ready }
@HiltViewModel
class RootViewModel @Inject constructor(
preferences: UserPreferencesRepository,
) : ViewModel() {
/**
* Set when onboarding finishes, so the switch happens immediately rather
* than waiting for the preference write to travel back through DataStore —
* which is fast, but not instant, and a visible flicker on the last tap of
* onboarding is a poor first impression.
*/
private val finishedThisSession = MutableStateFlow(false)
val state: StateFlow<RootState> =
combine(
preferences.preferences.map { it.onboardingCompleted },
finishedThisSession,
) { completed, finished ->
if (completed || finished) RootState.Ready else RootState.Onboarding
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), RootState.Loading)
fun onboardingFinished() { finishedThisSession.value = true }
}