Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Realm

Configurar y abrir un dominio - SDK de Kotlin

Esta página describe los archivos de dominio y cómo configurar, abrir y cerrar un dominio que solo conserva datos localmente. Para abrir un dominio que sincronice datos con Atlas mediante Sincronización de dispositivos, consulte Abrir un dominio sincronizado.

A realm is the core data structure used to organize data in Realm. Each realm is a collection of Realm objects: the objects that you use in your application as well as additional metadata that describe those objects. Each Realm object type has an object schema based on your defined object model.

Un esquema de dominio es una lista de los esquemas de objetos válidos que un dominio puede contener. El esquema se especifica al abrir el dominio. Si un dominio ya contiene datos al abrirlo, Realm valida cada objeto para garantizar que se haya proporcionado un esquema de objeto para su tipo y que cumpla con todas las restricciones especificadas en el esquema.

Realm almacena una versión codificada en binario de cada objeto y tipo en un reino en un solo .realm Archivo. Al abrir un dominio, Realm crea el archivo .realm si aún no existe. El archivo se encuentra en una ruta específica, que puedes definir al abrir el dominio.

Tip

Trabajar con archivos de Realm en Realm Studio

You can open, view, and edit the contents of realm files with Realm Studio.

Si no desea crear un archivo .realm ni sus archivos auxiliares asociados, puede abrir un dominio en memoria. Consulte la Abra una sección de Reino en memoria para obtener más información.

Realm crea archivos adicionales para cada realm:

  • archivos realm, con el sufijo "realm", por ejemplo, default.realm: contiene datos de objetos.

  • lock files, suffixed with "lock", e.g. default.realm.lock: keep track of which versions of data in a realm are actively in use. This prevents realm from reclaiming storage space that is still used by a client application.

  • note files, suffixed with "note", e.g. default.realm.note: enable inter-thread and inter-process notifications.

  • archivos de gestión, con el sufijo "gestión", pordefault.realm.management ejemplo: gestión del estado interno.

Deleting these files has important implications. For more information about deleting .realm or auxiliary files, see: Delete a Realm.

Para abrir un realm, crea un objeto RealmConfiguration que defina los detalles de un realm. Luego, pase el RealmConfiguration resultante a Realm.open().

Puede abrir un dominio con valores de configuración predeterminados o crear un RealmConfiguration con opciones de configuración adicionales. Sin embargo,debe pasar un parámetro de esquema que incluya todas las clases de objeto que desea usar en el dominio.

After you open the realm with the desired configuration, you can read and write data based on your defined schema.

Los ejemplos de esta página se refieren a los siguientes objetos Realm:

class Frog : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var name: String = ""
}
class Person : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var name: String = ""
}

To open a realm with default configuration values, use the RealmConfiguration.create(). method. You only need to define a set of object classes as the realm schema. Then, pass the RealmConfiguration to Realm.open().

El siguiente ejemplo abre un archivo default.realm en la ruta predeterminada con un esquema que incluye las clases Frog y Person:

// Creates a realm with default configuration values
val config = RealmConfiguration.create(
// Pass object classes for the realm schema
schema = setOf(Frog::class, Person::class)
)
// Open the realm with the configuration object
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration.name}")
// ... use the open realm ...

Si no define un directorio para el archivo de dominio, se usará la ubicación de almacenamiento de aplicaciones predeterminada para la plataforma. Puede encontrar el directorio predeterminado para su plataforma con lo siguiente:

  • Android: Context.getFiles()

  • JVM: System.getProperty("user.dir")

  • macOS: platform.Foundation.NSFileManager.defaultManager.currentDirectoryPath

  • iOS:

    NSFileManager.defaultManager.URLForDirectory(
    NSDocumentDirectory,
    NSUserDomainMask,
    null,
    true,
    null
    )

You can open a realm entirely in memory, which does not create a .realm file or its associated auxiliary files. Instead, the SDK stores objects in memory while the realm is open, and then discards the data when all instances are closed.

To open a realm that runs without being written to a file, build a RealmConfiguration with the RealmConfiguration.Builder using the inMemory property. Then, pass the resulting RealmConfiguration to Realm.open():

// Create the in-memory realm configuration
val config = RealmConfiguration.Builder(
schema = setOf(Frog::class, Person::class)
)
.inMemory()
.build()
// Open the realm with the configuration object
val realm = Realm.open(config)
Log.v("Successfully opened an in-memory realm")
// ... use the open realm ...

Nota

In-Memory Realms are Not Persisted

Because in-memory realms are not persisted, ensure you have at least one open instance of the realm for as long as you want to access the data. After you close the last instance of an in-memory realm, the data is no longer available.

You can add optional arguments to the RealmConfiguration to control the specifics of the realm that you would like to open, including:

For more information on specific configuration implementations, refer to Manage Realm Files - Kotlin SDK.

Para configurar un dominio con valores no predeterminados, cree el RealmConfiguration mediante RealmConfiguration.Builder.build() y pase las propiedades que desee configurar. Luego, pase el resultante RealmConfiguration a Realm.open().

En el siguiente ejemplo, el RealmConfiguration especifica un nombre personalizado, un directorio ("my-directory-path/myRealmName.realm") y una llave de cifrado:

// Create a realm configuration with configuration builder
// and pass all optional arguments
val config = RealmConfiguration.Builder(
schema = setOf(Frog::class, Person::class)
)
.name("myRealmName.realm")
.directory("my-directory-path")
.encryptionKey(myEncryptionKey)
.build()
// Open the realm with the configuration object
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration.name}")
// ... use the open realm ...

You can add initial data to a realm by using an initialDataCallback. The callback is triggered when the realm is opened for the first time.

val config = RealmConfiguration.Builder(
schema = setOf(Frog::class, Person::class)
)
.initialData {
copyToRealm(Frog().apply { name = "Kermit" })
copyToRealm(Person().apply { name = "Jim Henson" })
}
.build()
val realm = Realm.open(config)
Log.v("Successfully opened realm: ${realm.configuration.name}")
// Opened realm includes the initial data
val initialFrog = realm.query<Frog>().find().first()
val initialPerson = realm.query<Person>().find().first()
Log.v("Realm initialized with: ${initialFrog.name} and ${initialPerson.name}")

Para encontrar la ruta del .realm archivo, utilice la propiedad realm.configuration.path:

val realmPath = realm.configuration.path
Log.v("Realm path: $realmPath")

You close a realm with realm.close(). This method blocks until all write transactions on the realm have completed.

realm.close()

Advertencia

Close Realms to Prevent Memory Leaks

Es importante cerrar la instancia de tu reino para liberar recursos. No cerrar los reinos puede generar un error OutOfMemoryError.

To copy data from an existing realm to a new realm with different configuration options, pass the new configuration to the Realm.writeCopyTo() method. For example, you might copy data as a way to backup a local realm or to convert a synced realm to a local realm.

You can copy data to a realm that uses the same configuration:

  • Realm local a realm local

  • In-memory realm to in-memory realm

  • Reino sincronizado con reino sincronizado

You can copy data to a realm that uses different sync configurations:

  • Realm local a realm de sincronización basada en partición

  • Synced realm to local realm

  • Synced realm to a synced realm for a different user

Advertencia

You cannot copy data from a local realm to a Flexible Sync realm. You cannot copy between different sync configuration types, for example Partition-Based Sync to Flexible Sync.

You can also combine changes to the configuration. For example, you can copy data from an unencrypted, in-memory synced realm to an encrypted local realm.

Algunas consideraciones adicionales a tener en cuenta al utilizar Realm.writeCopyTo():

  • El archivo de destino no puede existir ya.

  • No se permite copiar un realm dentro de una transacción de escritura ni durante una migración.

  • Cuando uses Device Sync, debes sincronizar todos los cambios locales con el servidor antes de escribir la copia. Esto asegura que el archivo pueda ser usado como punto de partida para una aplicación recién instalada. Realm genera un error si hay cargas pendientes.

    You can use uploadAllLocalChanges() and downloadAllServerChanges() to ensure all sync processes are completed.

Ejemplo

Copy Data from Flexible Sync Realm to Local Realm

// Instantiate the synced realm with your App ID
val app = App.create(YOUR_APP_ID)
runBlocking {
val user = app.login(credentials)
// Create the synced realm configuration
val syncConfig = SyncConfiguration.Builder(user, setOf(Frog::class))
.initialSubscriptions { realm ->
add(realm.query<Frog>(),"all-frogs")
}
.build()
// Open the synced realm and add data to it
val syncRealm = Realm.open(syncConfig)
Log.v("Successfully opened realm: ${syncRealm.configuration.name}")
syncRealm.write {
this.copyToRealm(Frog().apply {
name = "Kermit"
})
}
// Wait for write to sync
syncRealm.syncSession.uploadAllLocalChanges(30.seconds)
// Create the local realm
val localConfig = RealmConfiguration.Builder(setOf(Frog::class))
.name("local.realm")
.build()
// Copy data from synced realm to the new realm
syncRealm.writeCopyTo(localConfig)
// Close the synced realm when you're done copying
syncRealm.close()
// Open the new local realm
val localRealm = Realm.open(localConfig)
// Copied Frog object is available in the new realm
val frog = localRealm.query<Frog>().find().first()
Log.v("Copied Frog: ${frog.name}")
localRealm.close()
}

You can also include a new encryption key in the copied realm's configuration or remove the encryption key from the new configuration.

Ejemplo

Copiar datos desde un Realm sin cifrar a un Realm cifrado

runBlocking {
// Create the unencrypted realm
val unencryptedConfig = RealmConfiguration.Builder(setOf(Frog::class))
.name("unencrypted.realm")
.build()
// Open the realm and add data to it
val unencryptedRealm = Realm.open(unencryptedConfig)
unencryptedRealm.write {
this.copyToRealm(Frog().apply {
name = "Kermit"
})
}
// ... Generate encryption key ...
// Create the encrypted realm
val encryptedConfig = RealmConfiguration.Builder(setOf(Frog::class))
.name("encrypted.realm")
.encryptionKey(encryptionKey)
.build()
// Copy data from `unencryptedRealm` to the new realm
// Data is encrypted as part of the copy process
unencryptedRealm.writeCopyTo(encryptedConfig)
// Close the original realm when you're done copying
unencryptedRealm.close()
// Open the new encrypted realm
val encryptedRealm = Realm.open(encryptedConfig)
// Copied Frog object is available in the new realm
val frog = encryptedRealm.query<Frog>().find().first()
Log.v("Copied Frog: ${frog.name}")
encryptedRealm.close()
}

Ejemplo

Copy Data from In-Memory to Local Realm

runBlocking {
// Create the in-memory realm
val inMemoryConfig = RealmConfiguration.Builder(setOf(Frog::class))
.name("inMemory.realm")
.inMemory()
.build()
// Open the realm and add data to it
val inMemoryRealm = Realm.open(inMemoryConfig)
inMemoryRealm.write {
this.copyToRealm(Frog().apply {
name = "Kermit"
})
}
// Create the local realm
val localConfig = RealmConfiguration.Builder(setOf(Frog::class))
.name("local.realm")
.build()
// Copy data from `inMemoryRealm` to the new realm
inMemoryRealm.writeCopyTo(localConfig)
// Close the original realm when you're done copying
inMemoryRealm.close()
// Open the new local realm
val localRealm = Realm.open(localConfig)
// Copied Frog object is available in the new realm
val frog = localRealm.query<Frog>().find().first()
Log.v("Copied Frog: ${frog.name}")
localRealm.close()
}

Volver

Datos del modelo con sincronización de dispositivos

En esta página