Thư viện DataStore lưu trữ dữ liệu một cách không đồng bộ, nhất quán và có thể chia sẻ, giúp khắc phục một số hạn chế của SharedPreferences. Trang này tập trung vào việc tạo DataStore trong các dự án Kotlin Multiplatform (KMP). Để biết thêm thông tin về DataStore, hãy xem tài liệu chính về DataStore và mẫu chính thức.
Thiết lập phần phụ thuộc
Để thiết lập DataStore trong dự án KMP, hãy thêm các phần phụ thuộc cho cấu phần phần mềm trong tệp build.gradle.kts
cho mô-đun của bạn:
commonMain.dependencies {
// DataStore library
implementation("androidx.datastore:datastore:1.1.7")
// The Preferences DataStore library
implementation("androidx.datastore:datastore-preferences:1.1.7")
}
Xác định các lớp DataStore
Bạn có thể xác định lớp DataStore
bằng DataStoreFactory
bên trong nguồn chung của mô-đun KMP dùng chung. Việc đặt các lớp này vào các nguồn chung cho phép chia sẻ các lớp này trên tất cả các nền tảng mục tiêu. Bạn có thể sử dụng các nội dung khai báo actual
và
expect
để tạo các phương thức triển khai
dành riêng cho nền tảng.
Tạo thực thể DataStore
Bạn cần xác định cách tạo bản sao đối tượng DataStore trên từng nền tảng. Đây là phần duy nhất của API bắt buộc phải có trong các nhóm tài nguyên nền tảng cụ thể do sự khác biệt trong các API hệ thống tệp.
Phổ biến
// shared/src/commonMain/kotlin/createDataStore.kt
/**
* Gets the singleton DataStore instance, creating it if necessary.
*/
fun createDataStore(producePath: () -> String): DataStore<Preferences> =
PreferenceDataStoreFactory.createWithPath(
produceFile = { producePath().toPath() }
)
internal const val dataStoreFileName = "dice.preferences_pb"
Android
Để tạo thực thể DataStore
trên Android, bạn cần có Context
cùng với đường dẫn.
// shared/src/androidMain/kotlin/createDataStore.android.kt
fun createDataStore(context: Context): DataStore<Preferences> = createDataStore(
producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }
)
iOS
Trên iOS, bạn có thể truy xuất đường dẫn từ NSDocumentDirectory
:
// shared/src/iosMain/kotlin/createDataStore.ios.kt
fun createDataStore(): DataStore<Preferences> = createDataStore(
producePath = {
val documentDirectory: NSURL? = NSFileManager.defaultManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = false,
error = null,
)
requireNotNull(documentDirectory).path + "/$dataStoreFileName"
}
)
JVM (Máy tính)
Để tạo thực thể DataStore
trên JVM (Máy tính), hãy cung cấp đường dẫn bằng cách sử dụng API Java hoặc Kotlin:
// shared/src/jvmMain/kotlin/createDataStore.desktop.kt
fun createDataStore(): DataStore<Preferences> = createDataStore(
producePath = {
val file = File(System.getProperty("java.io.tmpdir"), dataStoreFileName)
file.absolutePath
}
)