Open and Close a Realm

To open a synced realm, call getInstanceAsync(), passing in a a SyncConfiguration object. For example, the following code demonstrates how to create a realm with specific sync settings created using a SyncConfiguration object:

val user: User? = app.currentUser()
val partitionValue: String = "myPartition"
val config = SyncConfiguration.Builder(user!!, partitionValue).build()
val realm: Realm = Realm.getInstance(config)

The code above shows how to open the realm asynchronously by using getInstanceAsync(). You can also open a realm synchronously by using getInstance(), but this may lead to temporary data inconsistencies while the remote data is downloaded, and is generally not recommended.

Info With Circle IconCreated with Sketch.Note

To enable sync in your Android project, you need to configure it in the application-level build.gradle file by adding the following entry:

realm { syncEnabled = true }

For more information on enabling sync in Android, see Install Realm for Android.

When opening a local (non-synced) realm, set the default settings and then call getDefaultInstance():

val config = RealmConfiguration.Builder().build()
val realm: Realm = Realm.getDefaultInstance()

It is important to remember to call the close() method when done with a realm instance. Failing to do so can lead to OutOfMemoryError as the native resources cannot be freed.

Give Feedback