Android 的 Jetpack DataStore 的正确实例创建(alpha07 版本)

Proper instance creation of Android's Jetpack DataStore (alpha07 version)

因此,对于新的 alpha07 版本,Android 放弃了 private val dataStore = context.createDataStore(name = "settings_pref"),但是他们使用数据存储的新方式对我不起作用。

自从“androidx.datastore:datastore-core:1.0.0-alpha06”升级到 alpha07 后,我似乎无法在没有红色代码的情况下使我的数据存储区语法正常工作(错误出现在我添加 context.dataStore.edit)。还降级回 alpha06,以前工作的代码现在不再工作(使用 createDataStore)。

我使用的是他们在 main page 上的示例,但在其他任何地方,除了这个之外,他们仍然没有更新他们的示例。

@Singleton
 class PreferencesManager @Inject constructor(@ApplicationContext context: Context) {
    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
    
      
        val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
        val exampleCounterFlow: Flow<Int> = context.dataStore.data
            .map { preferences ->
                // No type safety.
                preferences[EXAMPLE_COUNTER] ?: 0
            }
    
        suspend fun incrementCounter() {
            context.dataStore.edit { settings ->
                val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
                settings[EXAMPLE_COUNTER] = currentCounterValue + 1
            }
        }
    }

如果有人知道这个问题(或我的错误),我将不胜感激。

这也让我很困惑,但我想通了(又名,猜测直到成功):

// Note: This is at the top level of the file, outside of any classes.
private val Context.dataStore by preferencesDataStore("user_preferences")

class UserPreferencesManager(context: Context) {
    private val dataStore = context.dataStore
    // ...
}

这适用于 DataStore<Preferences>,但如果您需要自定义序列化程序,您可以执行以下操作(与旧方法相同的参数):

// Still top level!
private val Context.dataStore by dataStore(
    fileName = "user_preferences",
    serializer = MyCustomSerializer,
)

我遇到了同样的问题,发现了一个错误:Context should be as a member of class to use it in any method:

private val Context.dataStore by preferencesDataStore("preferences")
class Preferenses(val context: Context) { get, set, etc}