DataStore 라이브러리는 비동기적이고 일관된 트랜잭션 방식으로 데이터를 저장하여 SharedPreferences의 일부 단점을 극복합니다. 이 페이지에서는 Kotlin 멀티플랫폼 (KMP) 프로젝트에서 DataStore를 만드는 방법을 중점적으로 설명합니다. DataStore에 관한 자세한 내용은 DataStore 기본 문서 및 공식 샘플을 참고하세요.
commonMain.dependencies{// DataStore libraryimplementation("androidx.datastore:datastore:1.1.7")// The Preferences DataStore libraryimplementation("androidx.datastore:datastore-preferences:1.1.7")}
DataStore 클래스 정의
공유 KMP 모듈의 공통 소스 내에서 DataStoreFactory를 사용하여 DataStore 클래스를 정의할 수 있습니다. 이러한 클래스를 공통 소스에 배치하면 모든 대상 플랫폼에서 공유할 수 있습니다. actual 및 expect 선언을 사용하여 플랫폼별 구현을 만들 수 있습니다.
DataStore 인스턴스 만들기
각 플랫폼에서 DataStore 객체를 인스턴스화하는 방법을 정의해야 합니다.
파일 시스템 API의 차이로 인해 특정 플랫폼 소스 세트에 있어야 하는 API의 유일한 부분입니다.
일반
// shared/src/commonMain/kotlin/createDataStore.kt/** * Gets the singleton DataStore instance, creating it if necessary. */funcreateDataStore(producePath:()->String):DataStore<Preferences>=PreferenceDataStoreFactory.createWithPath(produceFile={producePath().toPath()})internalconstvaldataStoreFileName="dice.preferences_pb"
Android
Android에서 DataStore 인스턴스를 만들려면 경로와 함께 Context가 필요합니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# DataStore (Kotlin Multiplatform)\n\nThe DataStore library stores data asynchronously, consistently, and\ntransactionally, overcoming some of the drawbacks of SharedPreferences. This\npage focuses on creating DataStore in Kotlin Multiplatform (KMP) projects. For\nmore information on DataStore, see the [primary documentation for DataStore](/topic/libraries/architecture/datastore)\nand [official samples](https://github.com/android/kotlin-multiplatform-samples).\n| **Note:** Only [DataStore Preferences](/topic/libraries/architecture/datastore#preferences-datastore) is supported in KMP projects.\n\nSet up dependencies\n-------------------\n\n| **Note:** DataStore supports KMP in versions 1.1.0 and higher.\n\nTo set up DataStore in your KMP project, add the dependencies for the artifacts\nin the `build.gradle.kts` file for your module: \n\n commonMain.dependencies {\n // DataStore library\n implementation(\"androidx.datastore:datastore:1.1.7\")\n // The Preferences DataStore library\n implementation(\"androidx.datastore:datastore-preferences:1.1.7\")\n }\n\nDefine the DataStore classes\n----------------------------\n\nYou can define the `DataStore` class with `DataStoreFactory` inside the common\nsource of your shared KMP module. Placing these classes in common sources allows\nthem to be shared across all target platforms. You can use [`actual` and\n`expect` declarations](https://kotlinlang.org/docs/multiplatform-expect-actual.html) to create platform-specific\nimplementations.\n\nCreate the DataStore instance\n-----------------------------\n\nYou need to define how to instantiate the DataStore object on each platform.\nThis is the only part of the API that is required to be in the specific platform\nsource sets due to the differences in file system APIs.\n\n### Common\n\n // shared/src/commonMain/kotlin/createDataStore.kt\n\n /**\n * Gets the singleton DataStore instance, creating it if necessary.\n */\n fun createDataStore(producePath: () -\u003e String): DataStore\u003cPreferences\u003e =\n PreferenceDataStoreFactory.createWithPath(\n produceFile = { producePath().toPath() }\n )\n\n internal const val dataStoreFileName = \"dice.preferences_pb\"\n\n### Android\n\nTo create the `DataStore` instance on Android, you need a [`Context`](/reference/android/content/Context) along\nwith the path. \n\n // shared/src/androidMain/kotlin/createDataStore.android.kt\n\n fun createDataStore(context: Context): DataStore\u003cPreferences\u003e = createDataStore(\n producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }\n )\n\n### iOS\n\nOn iOS, you can retrieve the path from the `NSDocumentDirectory`: \n\n // shared/src/iosMain/kotlin/createDataStore.ios.kt\n\n fun createDataStore(): DataStore\u003cPreferences\u003e = createDataStore(\n producePath = {\n val documentDirectory: NSURL? = NSFileManager.defaultManager.URLForDirectory(\n directory = NSDocumentDirectory,\n inDomain = NSUserDomainMask,\n appropriateForURL = null,\n create = false,\n error = null,\n )\n requireNotNull(documentDirectory).path + \"/$dataStoreFileName\"\n }\n )\n\n### JVM (Desktop)\n\nTo create the `DataStore` instance on JVM (Desktop), provide a path using Java\nor Kotlin APIs: \n\n // shared/src/jvmMain/kotlin/createDataStore.desktop.kt\n\n fun createDataStore(): DataStore\u003cPreferences\u003e = createDataStore(\n producePath = {\n val file = File(System.getProperty(\"java.io.tmpdir\"), dataStoreFileName)\n file.absolutePath\n }\n )\n\n| **Note:** `System.getProperty(\"java.io.tmpdir\")` points to the temporary folder on the system, which might be cleaned upon reboot. On macOS, you can instead use the `~/Library/Application Support/[your-app]` folder."]]