BackgroundSyncPreference.kt

1.2 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import dagger.hilt.android.qualifiers.ApplicationContext5import javax.inject.Inject6import javax.inject.Singleton7import kotlinx.coroutines.flow.MutableStateFlow8import kotlinx.coroutines.flow.StateFlow9import kotlinx.coroutines.flow.asStateFlow1011@Singleton12class BackgroundSyncPreference @Inject constructor(13    @ApplicationContext context: Context,14) {15    private val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)16    private val _enabled = MutableStateFlow(readEnabled(prefs.contains(KEY_ENABLED)) {17        prefs.getBoolean(KEY_ENABLED, true)18    })19    val enabled: StateFlow<Boolean> = _enabled.asStateFlow()2021    fun setEnabled(enabled: Boolean) {22        prefs.edit().putBoolean(KEY_ENABLED, enabled).apply()23        _enabled.value = enabled24    }2526    private companion object {27        const val PREFS_FILE = "peach_background_sync"28        const val KEY_ENABLED = "enabled"29    }30}3132// Existing paired installs default on so upgrading fixes the unreachable-phone state.33internal fun readEnabled(hasStoredChoice: Boolean, storedValue: () -> Boolean): Boolean =34    if (hasStoredChoice) storedValue() else true