Dev*_*inM 6 android android-lifecycle kotlin-flow android-jetpack-datastore
我正在使用 datastore-preferences:1.0.0-alpha01 并且当数据存储值更新时我似乎无法恢复事件。我一直试图在片段和父活动中观察它,结果相同。当我创建 DataStore 的实例并观察值流时,我在声明观察者后立即收到一个事件(注册观察者后似乎很常见)。这将表明流正在运行,并且观察者正在按预期接收事件。然后我在同一个观察者内部更新首选项的值,该观察者从不接收事件。
我使用这篇文章作为参考https://medium.com/scalereal/hello-datastore-bye-sharedpreferences-android-f46c610b81d5,它与我用来比较我的实现的 repo 一起使用。显然,这个是有效的。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 }
}
Run Code Online (Sandbox Code Playgroud)
更新连接对话框
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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当视图膨胀时,这就是我在日志中看到的
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
Run Code Online (Sandbox Code Playgroud)
现在,通过其他示例,我们应该看到观察者因已更新而触发事件,但我没有。对于其他示例,添加相同的日志记录点,很明显观察者收到了更新事件。
| 归档时间: |
|
| 查看次数: |
701 次 |
| 最近记录: |