Android DataStore:从 Java 调用 Context.createDataStore

ard*_*evd 5 android kotlin

我正在尝试用 Java 实现新的类型化 DataStore API,但遇到了一些问题。所有文档似乎都只在 Kotlin 中,并且尝试创建新的数据存储从 Java 方面看起来并不那么简单。

DataStoreFactoryKt.createDataStore()从 Java调用需要我提供所有参数,包括 Kotlin 实现中具有默认值的参数。@JvmOverloads该函数似乎没有任何注释,导致我的困境。

fun <T> Context.createDataStore(
    fileName: String,
    serializer: Serializer<T>,
    corruptionHandler: ReplaceFileCorruptionHandler<T>? = null,
    migrations: List<DataMigration<T>> = listOf(),
    scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
): DataStore<T> =
    DataStoreFactory.create(
        produceFile = { File(this.filesDir, "datastore/$fileName") },
        serializer = serializer,
        corruptionHandler = corruptionHandler,
        migrations = migrations,
        scope = scope
)
Run Code Online (Sandbox Code Playgroud)

如果有的话,有什么更好的方法来解决这个问题?或者 Data Store api 是否简单设计为仅与 Kotlin 一起使用?我不知道如何CoroutineScope从 Java 中提供一个论点。

Erc*_*can 7

将 dataStore 依赖项更新为“1.0.0-alpha08”后,如下所示。

// DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha08"
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式实现首选项:

private val Context.dataStore by preferencesDataStore("app_preferences")
Run Code Online (Sandbox Code Playgroud)

之后,如果您喜欢创建一些首选项键:

private object Keys {
    val HIDE_VISITED = booleanPreferencesKey("hide_visited")
}
Run Code Online (Sandbox Code Playgroud)

其他选项可以是字符串PreferencesKey、int PreferencesKey 等。

保存值示例:

context.dataStore.edit { prefs -> prefs[Keys.HIDE_VISITED] = hideVisited }
Run Code Online (Sandbox Code Playgroud)

读取保存值示例:

val hideVisited = preferences[Keys.HIDE_VISITED] ?: false
Run Code Online (Sandbox Code Playgroud)


Víc*_*tos 2

您需要将 DataStore首选项的依赖项添加到 Grade 构建文件中:

implementation "androidx.datastore:datastore-preferences:1.0.0-alpha04"
Run Code Online (Sandbox Code Playgroud)

而不是类型的方法,这样您就能够解析androidx.datastore.preferences.Context.createDataStore您期望的方法:

public fun Context.createDataStore(
    name: String,
    corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null,
    migrations: List<DataMigration<Preferences>> = listOf(),
    scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
): DataStore<Preferences> =
    PreferenceDataStoreFactory.create(
        corruptionHandler = corruptionHandler,
        migrations = migrations,
        scope = scope
    ) {
        File(this.filesDir, "datastore/$name.preferences_pb")
    }
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个解决方案。他无法继续使用旧版本的“DataStore”。更好的解决方案是解释如何使用较新的版本。 (3认同)