英文:
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
来合并databaseMode
和settingsState
流程。
可以像这样:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论