문서 메뉴

문서 홈애플리케이션 개발Atlas Device SDK

동기화된 Realm 구성 및 열기 - Kotlin SDK

이 페이지의 내용

  • 전제 조건
  • 동기화된 Realm 열기
  • 동기화된 Realm 구성
  • 열기 전에 변경 사항 다운로드
  • 열기 전에 조건부로 변경 사항 다운로드
  • 오프라인으로 동기화된 Realm 열기

이 페이지에서는 동기화된 데이터베이스를 여는 방법과 사용 가능한 다양한 구성 옵션에 대해 설명합니다.

클라이언트에서 동기화된 영역에 액세스하려면 먼저 다음을 수행해야 합니다.

  1. App Services UI에서 동기화를 활성화합니다 .

  2. Android 또는 코틀린 멀티플랫폼용 코틀린 SDK (Kotlin SDK)의 동기화 배포판을 설치합니다.

  3. 클라이언트 프로젝트에서 사용자를 인증합니다.

Flexible Sync Realm을 열려면 사용자와 Realm 객체 스키마 세트를 SyncConfiguration.Builder() 에 전달합니다. 다음으로, initialSubscriptions() 빌더 메서드를 사용하여 초기 구독 세트를 생성합니다. 마지막으로 구성을 Realm.open() 에 전달하여 Realm의 인스턴스를 엽니다.

val app = App.create(YOUR_APP_ID)
// use constants for query names so you can edit or remove them later
val NAME_QUERY = "NAME_QUERY"
runBlocking {
val user = app.login(Credentials.anonymous())
val config = SyncConfiguration.Builder(user, setOf(Toad::class))
.initialSubscriptions { realm ->
add(
realm.query<Toad>(
"name == $0",
"name value"
),
"subscription name"
)
}
.build()
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration.name}")
realm.close()
}

초기 구독으로 realm 부트스트랩하고 동기화된 realm 구독 managed에 대한 자세한 내용은 동기화 구독 managed 참조하세요.

특정 구성 설정을 조정하려면 SyncConfiguration.Builder에서 제공하는 옵션을 사용합니다.

val app = App.create(YOUR_APP_ID)
runBlocking {
val user = app.login(Credentials.anonymous())
val config = SyncConfiguration.Builder(user, setOf(Toad::class))
.maxNumberOfActiveVersions(10)
.name("realm name")
.initialSubscriptions { realm ->
add(
realm.query<Toad>(
"name == $0",
"name value"
),
"subscription name"
)
}
.build()
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration}")
realm.close()
}

버전 1.13.0의 새로운 기능: 동기화 시간 초과 구성 옵션 추가

Kotlin v1.13.0에서는 동기화 작업에 사용되는 다양한 기본 시간 제한을 재정의할 수 있습니다. App 클라이언트 구성에서 이러한 제한 시간을 설정할 수 있으며, 이는 앱의 모든 동기화 세션에 적용됩니다. 방법을 알아보려면 동기화 시간 초과 구성을 참조하세요.

Kotlin SDK로 동기화된 Realm을 열 때 Realm을 열기 전에 .waitForInitialRemoteData() 함수를 사용하여 앱에서 변경 세트를 다운로드할 수 있습니다. 이 옵션을 설정하면 모든 데이터가 다운로드될 때까지 Realm이 열리지 않습니다. 장치가 오프라인 상태인 경우 Realm 열기가 차단됩니다. 초기 데이터 다운로드는 시간이 오래 걸릴 수 있으므로 백그라운드 스레드에서 이 설정을 사용하여 Realm을 열어야 합니다.

이 함수는 타임 아웃 을 허용합니다. . 다운로드가 제한 시간을 초과하면 Realm은 DownloadingRealmTimeoutException을 발생시킵니다.

val user = app.login(Credentials.emailPassword(email, password))
val config = SyncConfiguration.Builder(user, setOf(Toad::class))
.waitForInitialRemoteData(60.seconds)
.initialSubscriptions { realm ->
add(
realm.query<Toad>(
"name == $0",
"Jeremiah"
),
"toads_named_jeremiah"
)
}
.build()
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration}")
// Query the realm we opened after waiting for data to download, and see that it contains data
val downloadedToads: RealmResults<Toad> = realm.query<Toad>().find()
Log.v("After downloading initial data, downloadedToads.size is ${downloadedToads.size}")
realm.close()

앱이 Realm을 열기 전에 서버 데이터를 다운로드해야 하는지 여부를 결정하는 조건이 있는 경우, 이를 SyncSession.downloadAllServerChanges() 와 함께 사용하여 Realm을 열기 전에 조건부로 변경 사항을 다운로드할 수 있습니다. 이 메서드를 호출하면 알려진 모든 원격 변경 사항이 다운로드되어 Realm에 적용될 때까지 또는 지정된 시간 초과에 도달할 때까지 차단됩니다. 이 메서드는 UI가 아닌 스레드에서만 호출해야 합니다.

이 함수는 타임아웃 Duration을 허용합니다.

val user = app.login(Credentials.emailPassword(email, password))
val config = SyncConfiguration.Builder(user, setOf(Toad::class))
.initialSubscriptions { realm ->
add(
realm.query<Toad>(
"name == $0",
"Lollihops"
),
"toads_named_lollihops"
)
}
.build()
val realm = Realm.open(config)
// Conditionally download data before using the realm based on some business logic
if (downloadData) {
realm.syncSession.downloadAllServerChanges(30.seconds)
}
// Query the realm we opened after waiting for data to download, and see that it contains data
val downloadedToads: RealmResults<Toad> = realm.query<Toad>().find()
Log.v("After conditionally downloading data, downloadedToads.size is ${downloadedToads.size}")
realm.close()

Realm 애플리케이션이 사용자를 인증하면 사용자의 자격 증명을 캐시합니다. 기존 사용자 자격 증명을 확인하여 로그인 흐름을 우회하고 캐시된 사용자에 액세스할 수 있습니다. 이 기능을 사용하여 오프라인에서 Realm을 열 수 있습니다.

참고

최초 로그인 시에는 네트워크 연결이 필요합니다.

사용자가 앱에 가입하거나 클라이언트의 기존 계정으로 처음으로 로그인하는 경우 클라이언트가 네트워크에 연결되어 있어야 합니다. 캐시된 사용자 자격 증명을 확인하면 오프라인에서 Realm을 열 수 있지만 이는 사용자가 이전에 온라인 상태에서 로그인한 적이 있는 경우에만 가능합니다.

Realm 을 열기 전에 클라이언트 앱에서 변경 사항을 다운로드할 필요가 없는 경우에만 동기화된 Realm을 오프라인으로 열 수 있습니다.

// You can only open a synced realm offline if there is a cached user credential. If
// there is no app.currentUser, you must log them in, which requires a network connection.
if (app.currentUser == null) {
app.login(Credentials.emailPassword(email, password))
}
// If the app.currentUser isn't null, you can use the cached credential to open the synced
// realm even if the user is offline.
val user = app.currentUser!!
val realm = Realm.open(config)
// Query the realm we opened, and see that it contains data
val offlineToads: RealmResults<Toad> = realm.query<Toad>().find()
Log.v("After opening a realm offline, offlineToads.size is ${offlineToads.size}")
realm.close()
← 앱에 Device Sync 추가 - Kotlin SDK