KMP용 DataStore 설정

DataStore 라이브러리는 비동기적이고 일관된 트랜잭션 방식으로 데이터를 저장하여 SharedPreferences의 일부 단점을 극복합니다. 이 페이지에서는 Kotlin 멀티플랫폼 (KMP) 프로젝트에서 DataStore를 만드는 데 중점을 둡니다. DataStore에 관한 자세한 내용은 DataStore 기본 문서공식 샘플을 참고하세요.

종속 항목 설정

KMP 프로젝트에서 DataStore를 설정하려면 모듈의 build.gradle.kts 파일에 아티팩트의 종속 항목을 추가하세요.

commonMain.dependencies {
  // DataStore library
  implementation("androidx.datastore:datastore:1.1.7")
  // The Preferences DataStore library
  implementation("androidx.datastore:datastore-preferences:1.1.7")
}

DataStore 클래스 정의

공유 KMP 모듈의 공통 소스 내에서 DataStoreFactory를 사용하여 DataStore 클래스를 정의할 수 있습니다. 이러한 클래스를 공통 소스에 배치하면 모든 타겟 플랫폼에서 공유할 수 있습니다. actualexpect 선언을 사용하여 플랫폼별 구현을 만들 수 있습니다.

Datastore 인스턴스 만들기

각 플랫폼에서 DataStore 객체를 인스턴스화하는 방법을 정의해야 합니다. 파일 시스템 API의 차이로 인해 특정 플랫폼 소스 세트에 있어야 하는 API의 유일한 부분입니다.

일반

// 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

Android에서 DataStore 인스턴스를 만들려면 경로와 함께 Context가 필요합니다.

// shared/src/androidMain/kotlin/createDataStore.android.kt

fun createDataStore(context: Context): DataStore<Preferences> = createDataStore(
    producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }
)

iOS

iOS에서는 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 (데스크톱)

JVM (데스크톱)에서 DataStore 인스턴스를 만들려면 Java 또는 Kotlin API를 사용하여 경로를 제공하세요.

// shared/src/jvmMain/kotlin/createDataStore.desktop.kt

fun createDataStore(): DataStore<Preferences> = createDataStore(
    producePath = {
      val file = File(System.getProperty("java.io.tmpdir"), dataStoreFileName)
      file.absolutePath
    }
)