数据存储偏好在Kotlin和协程中不起作用

huangapple go评论80阅读模式
英文:

Data store preferences is not working with Kotlin and Coroutines

问题

我想保存所选的数据库模式并显示当前模式。

英文:

I have a problem with data store preferences. I trying to save chosen database mode and display the current one in the settings screen, but I don't know why it's not working. I don't have any errors. I tried debugging the code, but the debugger is not going into the coroutine block.

class SettingsRepository @Inject constructor(
    private val dataStore: DataStore<Preferences>
) {
    val databaseMode: Flow<String?>
        get() =
            dataStore.data.map { preferences ->
                preferences[DATABASE_MODE_KEY]
            }

    suspend fun updateDatabaseMode(databaseMode: String) {
        dataStore.edit { preferences ->
            preferences[DATABASE_MODE_KEY] = databaseMode
        }
    }

    companion object {
        val DATABASE_MODE_KEY = stringPreferencesKey("database_mode")
    }
}
@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository
) : ViewModel() {
    private val _settingsState = MutableStateFlow(SettingsState())
    var settingsState: StateFlow<SettingsState> = _settingsState.asStateFlow()

    init {
        viewModelScope.launch {
            settingsRepository.databaseMode.map { mode ->
                _settingsState.update {
                    it.copy(
                        databaseMode = mode ?: DatabaseMode.LOCAL.name
                    )
                }
            }
        }
    }

    fun onChangeDatabaseMode(databaseMode: String) {
        viewModelScope.launch {
            settingsRepository.updateDatabaseMode(databaseMode)
        }
        _settingsState.update {
            it.copy(
                databaseMode = databaseMode,
                showDatabaseModeDropdown = false
            )
        }
    }
[...]

I want to save the chosen database mode and display the current one.

答案1

得分: 0

根据您的代码,我看到databaseMode流程从未被收集,所以init块中的map从未被调用。

我建议在这种情况下使用combine来合并databaseModesettingsState流程。

可以像这样:

val databaseModeFlow = settingsRepository.databaseMode
val combinedFlow = settingsState.combine(databaseModeFlow) { s, d ->
    s.copy(databaseMode = d)
}

并且应该移除init块。

英文:

As I can see in you code databaseMode flow is never collected so map in init block never called.

I would suggest using combine for databaseMode and settingsState flows in this case.

Something like this:

val databaseModeFlow = settingsRepository.databaseMode
val combinedFlow = settingsState.combine(databaseMode){ s, d ->
    s.copy(databaseMode = d)
}

And init block should be removed.

huangapple
  • 本文由 发表于 2023年4月17日 16:36:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定