the great warrior
12/04/2022, 6:54 PM@Singleton
class DataStorePreference @Inject constructor(@ApplicationContext context: Context) {
private val dataSource = context.dataStore
companion object {
const val CALCULATOR_USER_PREFERENCES = "CALCULATOR_USER_PREFERENCES"
val CURRENT_INPUT = stringPreferencesKey("CURRENT_INPUT")
}
suspend fun <T> getPreference(key: Preferences.Key<T>, defaultValue: T):
Flow<T> = dataSource.data.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
val result = preferences[key] ?: defaultValue
result
}
}
@HiltViewModel
class CalculatorViewModel @Inject constructor(
private val dataStorePreferenceRepository: DataStorePreferenceRepository
) : ViewModel() {
// pass CURRENT_INPUT preference value to mutableStateFlow initial value
private val _currentInput: MutableStateFlow<String?> = MutableStateFlow(null)
val currentInput = _currentInput.asStateFlow()
suspend fun<T> getPreference(key: Preferences.Key<T>, defaultValue : T) =
dataStorePreferenceRepository.getPreference(key, defaultValue)
}
Jan Fidor
12/05/2022, 11:19 AM