Navigation

Frozen Architecture - Kotlin Multiplatform SDK

Unlike the other MongoDB Realm SDKs, the Kotlin SDK does not provide live objects and collections that update simultaneously with underlying data. Instead, the Kotlin SDK works exclusively with frozen objects that can be passed between threads safely.

Because frozen objects don't automatically update when data changes in your realm, they work a little differently from the live objects you may have used in other Realm SDKs.

The Realm class is no longer thread-confined, so you can share a single realm across multiple threads. You no longer need to handle the realm lifecycle explicitly with calls to Realm.close().

To access changes to objects and collections, use Coroutines and the Flow API. Changes are thread-safe, so you can access them from any context. Notifications are handled on a dedicated internal notifier thread. Frozen objects now support change listeners.

val config = RealmConfiguration(schema = setOf(Task::class))
val realm = Realm(config)
// fetch objects from a realm as Flowables
CoroutineScope(Dispatchers.Main).launch {
val flow: Flow<RealmResults<Task>> = realm.objects(Task::class).observe()
flow.collect { task ->
println("Task: $task")
}
}
// write an object to the realm in a coroutine
CoroutineScope(Dispatchers.Main).launch {
realm.write {
this.copyToRealm(Task().apply { name = "my task"; status = "Open"})
}
}
Note
Flows API Requires Kotlinx Coroutines

To use the Flows API in your KMM project, install the kotlinx.coroutines library.

Just like in other Realm SDKs, write transactions implicitly advance your realm to the most recent version of data stored on disk.

Realm objects are still lazy-loaded by default. This allows you to query large collections of objects without reading large amounts of data from disk. This also means that the first access to a field of an object will always return the most recent data.

Objects fetched within a write transaction are live objects that automatically update during that write transaction. Objects returned from a write closure become frozen objects when the write transaction completes.

Give Feedback