Hi guys, I have a data store preference value name...
# android
t
Hi guys, I have a data store preference value named CURRENT_INPUT and I want to pass it to mutableStateFlow as initial value, but I don't know how to do it. Here's the code.
Copy code
@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
    }
}
Copy code
@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)
}
👀 1
j
Hi, I'm not certain if that's what you're going for, but you can try using __currentInput.emit(CURRENT__INPUT) or __currentInput.value = CURRENT_INPUT depending which best fits the usecase