我已经使用 Datastore 很长时间了。今天我不得不阅读主线程中的值。在查看文档后,我决定使用runblocking。我创建了一个名为 lastInsertedId 的长值。
我在片段 A 中读取 lastInsertedId,然后导航到片段 B,我正在更改 lastInsertedId 的值。当我弹回片段 A 时,我再次阅读 lastInsertedId。但是 lastInsertedId 的值还是一样的。实际上它的值正在改变,但我无法读取它的最后一个值。
我认为这是因为片段 A 没有被破坏。只有 onDestroyView 从 onCreateView 调用和创建。我想要的是我需要在主线程中随时访问 lastInsertedID 的当前值。
当我将它创建为变量时,它总是返回相同的值。但是当我将它转换为功能时,它运行良好。但我认为这不是最佳做法。访问此值的最佳方法是什么?谢谢。
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "main")
@Singleton
class DataStoreManager @Inject constructor(@ApplicationContext appContext: Context) {
private val mainDataStore = appContext.dataStore
suspend fun setLastInsertedId(lastId: Long) {
mainDataStore.edit { main ->
main[LAST_INSERTED_ID] = lastId
}
}
// Returns always the same value
val lastInsertedId: Long = runBlocking {
mainDataStore.data.map { preferences ->
preferences[LAST_INSERTED_ID] ?: 0
}.first()
}
// Returns as expected
fun lastInsertedId(): Long = runBlocking {
mainDataStore.data.map { preferences ->
preferences[LAST_INSERTED_ID] ?: 0
}.first()
}
// This is also work perfectly but i need to access in main thread.
val lastInsertedId : Flow<Long> = mainDataStore.data.map { preferences ->
preferences[LAST_INSERTED_ID] ?: Constants.DEFAULT_FOOD_ID
}
companion object {
private val LAST_INSERTED_ID = longPreferencesKey("last_inserted_id")
}
}