我正在使用 datastore-preferences:1.0.0-alpha01 并且在更新数据存储区值时似乎无法恢复事件。我一直试图在片段和父活动中以相同的结果观察它。当我创建 DataStore 的实例并观察值流时,我在声明观察者后立即收到一个事件(在注册观察者后似乎很常见)。这将表明流程正在运行,并且观察者正在按预期接收事件。然后,我在从不接收事件的同一观察者内部更新首选项的值。
我使用这篇文章作为参考https://medium.com/scalereal/hello-datastore-bye-sharedpreferences-android-f46c610b81d5与我用来比较我的实现的存储库一起使用。显然,这个有效。https://github.com/PatilShreyas/DataStoreExample
数据存储实用程序
class DataStoreUtils(context: Context) {
companion object {
private const val TAG = "DataStoreUtils"
}
private val dataStore = context.createDataStore(name = Constants.PrefName.APP_PREFS)
suspend fun setString(prefKey: String, value: String) {
Log.d(TAG, "Setting $prefKey to $value")
dataStore.edit { it[preferencesKey<String>(prefKey)] = value }
}
suspend fun getString(prefKey: String): String? {
return dataStore.data.map { it[preferencesKey<String>(prefKey)] ?: return@map null }.first()
}
val usernameFlow: Flow<String?> = dataStore.data
.catch {
if (it is IOException) {
it.printStackTrace()
emit(emptyPreferences())
}
else { throw it }
}
.map { it[preferencesKey(Constants.SharedPrefKeys.USERNAME)] ?: return@map null }
}
更新连接对话框
class UpdateConnectionDialog : DialogFragment() {
companion object {
private const val TAG = "UpdateConnectionDialog"
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
save_btn.setOnClickListener {
runBlocking { authenticateResponse(ApiCalls.postLogin(body)!!) }
}
}
override fun onResume() {
super.onResume()
dataStore ?: dataStore = DataStoreUtils(Application.appInstance?.applicationContext!!)
dataStore.usernameFlow.asLiveData().observe(this) {
Log.d(TAG, "Updated username to: $it")
}
}
private fun authenticateResponse(response: ApiResponse<String>) {
Log.d(TAG, "Auth request made.")
when (response) {
is ApiSuccessResponse<String> -> {
AppLog.d(TAG, "Auth Success")
lifecycleScope.launch {
dataStore.setString(Constants.PrefKeys.USERNAME, username_input.text.toString())
dataStore.setString(Constants.PrefKeys.PASSWORD, password_input.text.toString())
}
}
is ApiErrorResponse<String> -> {
AppLog.d(TAG, "Auth failed")
}
}
}
}
当视图膨胀时,这就是我在日志中看到的
D/UpdateConnectionDialog: onCreateView()
D/UpdateConnectionDialog: onViewCreated()
D/UpdateConnectionDialog: onResume()
D/UpdateConnectionDialog: Updated username to: X // Seems to be common with other examples I have found. After registering an observer it immediately triggers the event.
D/UpdateConnectionDialog: Auth request made.
D/UpdateConnectionDialog: Auth Success
D/DataStoreUtils: Setting USERNAME to X
D/DataStoreUtils: Setting PASSWORD to X
现在,通过其他示例,我们应该看到观察者触发了一个已更新的事件,但我没有。对于其他示例,添加相同的日志记录点,很明显观察者收到了更新事件。