Docs Menu
Docs Home
/ /
Atlas Device SDK
/ / /

Realm 번들 - Kotlin SDK

이 페이지의 내용

  • 개요
  • 플랫폼별 자산 Realm 위치
  • 동기화되지 않은 Realm 번들
  • 시드 데이터로 자산 Realm 채우기
  • 프로덕션 애플리케이션에서 Realm 파일 번들 및 열기
  • 동기화된 Realm 번들
  • 시드 데이터로 자산 Realm 채우기
  • 자산 Realm 사본 만들기
  • 프로덕션 애플리케이션에서 동기화된 Realm 파일 번들 및 열기

버전 1.9.0의 새로운 기능

Realm 코틀린 SDK (Kotlin SDK)는 애플리케이션과 함께 Realm 파일 번들을 지원합니다. 이를 통해 애플리케이션 다운로드에서 시드 데이터로 데이터베이스를 미리 채울 수 있습니다.

초기 데이터 콜백 또는 초기 구독 고려

애플리케이션에서 InitialDataCallback 또는 InitialSubscriptions를 사용하여 Realm을 처음 열 때 데이터를 Realm에 추가할 수도 있습니다.

Realm Kotlin SDK는 번들 자산/리소스에 대한 플랫폼의 기존 위치를 기반으로 시드 데이터가 포함된 영역 Realm을 찾습니다.

  • Android: android.content.res.AssetManager.open(assetFilename)을(를) 통해

  • JVM: Class<T>.javaClass.classLoader.getResource(assetFilename)

  • Darwin: NSBundle.mainBundle.pathForResource(assetFilenameBase, assetFilenameExtension)

자산 Realm을 생성한 후에는 적절한 위치에 배치해야 합니다. Realm을 처음 열 때 자산 Realm을 찾을 수 없는 경우 Realm.open() IllegalArgumentException 과 함께 실패합니다.

1
  1. 새 임시 프로젝트를 생성하여 자산 영역을 생성하고 시드 데이터로 채웁니다. 이 프로젝트는 프로덕션 앱과 동일한 Realm 객체 스키마 를 사용합니다.

  2. 시드하려는 데이터가 있는 기존 Realm 을 열거나 새 Realm을 만듭니다. 자산 Realm의 특정 이름 을 설정하여 앱의 초기 데이터 소스로 이름으로 참조할 수 있도록 합니다.

  3. 프로덕션 애플리케이션에 포함할 시드 데이터로 자산 영역을 채웁니다.

    Realm.configuration.path를 사용하여 자산 영역 파일의 경로를 가져올 수 있습니다.

// Open a local realm to use as the asset realm
val config = RealmConfiguration.Builder(schema = setOf(Item::class))
.name("asset.realm")
.build()
val assetRealm = Realm.open(config)
assetRealm.writeBlocking {
// Add seed data to the asset realm
copyToRealm(Item().apply {
summary = "Write an awesome app"
isComplete = false
})
}
// Verify the data in the existing realm
// (this data should also be in the bundled realm we open later)
val originalItems: RealmResults<Item> = assetRealm.query<Item>().find()
for(item in originalItems) {
Log.v("Item in the assetRealm: ${item.summary}")
}
// Get the path to the realm
Log.v("Realm location: ${config.path}")
assetRealm.close()

이제 자산 영역이 있으므로 프로덕션 애플리케이션으로 이동하여 사용할 수 있습니다.

Realm은 여러 SDK와 호환됩니다.

동일한 파일 형식을 사용하는 Realm 파일은 여러 SDK와 호환됩니다. 프로덕션 애플리케이션과 번들로 사용할 자산 Realm을 프로그래밍 방식으로 생성해야 하는 경우 Node.js SDK 를 사용하여 CI 파이프라인과 쉽게 통합할 수 있습니다.

SDK의 변경 로그에서 SDK 버전이 지원하는 파일 형식을 찾을 수 있습니다. 이는 '파일 형식: 파일 형식 v23으로 Realms 생성'과 유사할 수 있습니다.

2
  1. 자산 Realm 파일의 사본을 프로덕션 애플리케이션에 저장합니다. 이 자산 파일을 앱 플랫폼에 적합한 위치에 배치해야 합니다. 자세한 내용 은 플랫폼별 자산 Realm 위치를 참조하세요.

  2. 프로덕션 앱이 자산 Realm을 여는 데 사용할 수 있는 구성 을 생성합니다. 이 구성의 initialRealmFile 속성을 자산 영역의 이름으로 설정합니다.

    선택적으로 initialRealmFilesha256checkSum 를 제공하여 Realm 파일을 열 때 무결성을 확인할 수 있습니다. 시드 영역을 열 때 자산 파일의 계산된 체크섬과 일치하지 않는 체크섬을 제공하면 Realm.open() 가 실패하고 IllegalArgumentException 이 표시됩니다.

  3. 이 구성을 사용하면 번들로 제공되는 자산 영역을 열 수 있습니다. 여기에는 복사 당시 자산 영역에 있던 데이터가 포함되어 있습니다.

// The config should list the bundled asset realm as the initialRealmFile
val bundledRealmConfig = RealmConfiguration.Builder(schema = setOf(Item::class))
.initialRealmFile("asset.realm")
.build()
// After moving the bundled realm to the appropriate location for your app's platform,
// open and use the bundled realm as usual.
val bundledRealm = Realm.open(bundledRealmConfig)
val bundledItems: RealmResults<Item> = bundledRealm.query<Item>().find()
for(item in bundledItems) {
Log.v("Item in the bundledRealm: ${item.summary}")
}
bundledRealm.close()

동기화된 영역을 번들로 제공하면 사용자가 동기화된 영역을 사용할 때 처음 열 때 다운로드해야 하는 데이터의 크기가 줄어들지만 앱의 다운로드 파일 크기는 늘어나게 됩니다. 애플리케이션과 자산 Realm을 번들로 제공하는 경우 사용자가 Realm을 열 때 다운로드해야 하는 유일한 데이터는 자산 Realm을 준비한 이후 발생한 변경 사항입니다.

중요

동기화된 Realm 번들

백엔드 애플리케이션에서 Flexible Sync 를 사용하는 경우 사용자가 번들 Realm 파일을 처음 열 때 클라이언트 재설정을 경험할 수 있습니다. 이 문제는 클라이언트 최대 오프라인 시간 이 활성화된 경우(클라이언트 최대 오프라인 시간은 기본적으로 활성화되어 있음) 발생할 수 있습니다. 사용자가 처음 동기화하기 전에 번들 Realm 파일이 클라이언트 최대 오프라인 시간 설정에 지정된 일수보다 오래 생성된 경우 사용자는 클라이언트 재설정을 경험하게 됩니다.

클라이언트 재설정을 수행하는 애플리케이션은 애플리케이션 백엔드에서 영역의 전체 상태를 다운로드합니다. 이렇게 하면 Realm 파일을 번들로 제공할 때 얻을 수 있는 이점이 무효화됩니다. 클라이언트 재설정을 방지하고 Realm 파일 번들의 이점을 보존하려면 다음을 수행합니다.

  • 동기화된 영역을 번들로 제공하는 애플리케이션에서는 클라이언트 최대 오프라인 시간을 사용하지 않도록 합니다.

  • 애플리케이션에서 클라이언트 최대 오프라인 시간을 사용하는 경우 애플리케이션 다운로드에 항상 최근에 동기화된 Realm 파일이 포함되어 있는지 확인하세요. 각 애플리케이션 버전마다 새 파일을 생성하고 클라이언트 최대 오프라인 시간 (일)을 초과하는 버전이 최신 상태로 유지되지 않도록 합니다.

애플리케이션에서 Flexible Sync 를 사용하는 경우 동기화된 자산 Realm을 번들로 묶는 대신 초기 동기화 구독을 사용하여 데이터로 애플리케이션을 채울 수 있습니다. 초기 구독을 사용하면 데이터가 클라이언트의 최대 오프라인 시간보다 오래된 것을 걱정할 필요가 없습니다. 동기화 구독 사용에 대해 자세히 알아보려면 구독을 참조하세요 .

동기화 영역을 번들로 구성하려면 다음을 수행합니다.

1
  1. 새 임시 프로젝트를 생성하여 자산 Realm을 생성하고 채웁니다. 이 프로젝트는 프로덕션 앱과 동일한 Realm 객체 스키마 를 사용합니다.

  2. 자산 Realm으로 사용하려는 동기화 Realm을 엽니다 .

  3. 프로덕션 애플리케이션에 포함하려는 시드 데이터로 자산 영역을 채웁니다. 모든 로컬 변경 사항이 Device Sync 서버와 동기화될 때까지 기다려야 합니다. uploadAllLocalChanges()downloadAllServerChanges() 를 사용하여 모든 동기화 프로세스가 완료되었는지 확인합니다.

val app = App.create(yourFlexAppId)
// Login with user that has the server-side permissions to
// read and write the data you want in the asset realm
val user = app.login(credentials)
// Create a SyncConfiguration to open a synced realm to use as the asset realm
val assetRealmConfig = SyncConfiguration.Builder(user, setOf(Item::class))
.name("asset.realm")
// Add a subscription that matches the data being added
// and your app's backend permissions
.initialSubscriptions{ realm ->
add(
realm.query<Item>("isComplete == $0", false), "Incomplete Items")
}
.build()
val assetRealm = Realm.open(assetRealmConfig)
assetRealm.subscriptions.waitForSynchronization(10.seconds)
assertEquals(SubscriptionSetState.COMPLETE, assetRealm.subscriptions.state)
assetRealm.writeBlocking {
// Add seed data to the synced realm
copyToRealm(Item().apply {
summary = "Make sure the app has the data it needs"
isComplete = false
})
}
// Verify the data in the existing realm
// (this data should also be in the bundled realm we open later)
val assetItems: RealmResults<Item> = assetRealm.query<Item>().find()
for(item in assetItems) {
Log.v("Item in the assetRealm: ${item.summary}")
}
// IMPORTANT: Sync all changes with server before copying the synced realm
assetRealm.syncSession.uploadAllLocalChanges(30.seconds)
assetRealm.syncSession.downloadAllServerChanges(30.seconds)
2

프로덕션 애플리케이션과 함께 번들로 제공할 수 있는 임시 프로젝트에서 자산 영역의 복사본을 생성해야 합니다.

  1. 앱이 자산 Realm의 사본을 여는 데 사용할 수 있는 SyncConfiguration 을 생성합니다. 이 구성의 initialRealmFile 속성을 자산 영역의 이름으로 설정합니다.

    선택적으로 initialRealmFilesha256checkSum 를 제공하여 Realm 파일을 열 때 무결성을 확인할 수 있습니다. 시드 영역을 열 때 시드 영역의 계산된 체크섬과 일치하지 않는 체크섬을 제공하면 Realm.open() 가 실패하고 IllegalArgumentException 이 표시됩니다.

    // Create a SyncConfiguration for the bundled copy.
    // The initialRealmFile value is the `name` property of the asset realm you're bundling.
    val copyConfig = SyncConfiguration.Builder(user, setOf(Item::class))
    .initialRealmFile("asset.realm")
    .build()
  2. writeCopyTo() 를 사용하여 동기화된 Realm의 새 버전을 만듭니다. 동기화된 Realm을 번들로 묶으려면 writeCopyTo()사용해야 합니다 . 이 메서드는 Realm을 사용자와 연결하는 메타데이터를 제거하여 다른 사용자가 Realm 파일을 열 수 있도록 합니다.

    Realm.configuration.path를 사용하여 복사된 Realm 파일의 경로를 가져옵니다.

    // Copy the synced realm with writeCopyTo()
    assetRealm.writeCopyTo(copyConfig)
    // Get the path to the copy you just created.
    // You must move this file into the appropriate location for your app's platform.
    Log.v("Bundled realm location: ${copyConfig.path}")
    assetRealm.close()

이제 자산 영역의 사본이 있으므로 프로덕션 애플리케이션으로 이동하여 사용할 수 있습니다.

3
  1. 자산 Realm 파일의 사본을 프로덕션 애플리케이션에 저장합니다. 이 자산 파일을 앱 플랫폼에 적합한 위치에 배치해야 합니다. 자세한 내용 은 플랫폼별 자산 Realm 위치를 참조하세요.

  2. 이제 앱과 함께 번들로 제공되는 자산 영역의 복사본이 있으므로 생성한 복사된 영역 구성을 사용하여 열 수 있습니다. 여기에는 복사 당시 자산 Realm에 있던 데이터가 포함되어 있습니다.

// After moving the bundled realm to the appropriate location for your app's platform,
// open and use the bundled realm as usual.
val copiedRealm = Realm.open(copyConfig)
// This should contain the same Items as in the asset realm
val copiedItems: RealmResults<Item> = copiedRealm.query<Item>().find()
for(item in copiedItems) {
Log.v("Item in the copiedRealm: ${item.summary}")
}
copiedRealm.close()

돌아가기

Realm 암호화