Un dominio es un conjunto de objetos relacionados que se ajustan a un esquema predefinido. Los dominios pueden contener más de un tipo de datos, siempre que exista un esquema para cada tipo.
Cada reino almacena datos en un archivo de reino independiente que contiene la codificación binaria de cada objeto del reino. Puedes... sincronizar el reino en múltiples dispositivos y configurar controladores de eventos reactivos que llamen a una función cada vez que se crea, modifica o elimina un objeto en un reino.
The Realm Lifecycle
Every realm instance consumes a significant amount of resources. Opening and closing a realm are both expensive operations, but keeping a realm open also incurs significant resource overhead. To maximize the performance of your application, you should minimize the number of open realms at any given time and limit the number of open and close operations used.
However, opening a realm is not always consistently expensive. If the realm is already open within the same process or thread, opening an additional instance requires fewer resources:
Si el realm no se abre en el mismo proceso, abrir el realm es costoso.
If the realm is already open on a different thread within the same process, opening the realm is less expensive, but still nontrivial.
Si el realm ya está abierto en el mismo thread dentro del mismo proceso, abrir el realm requiere mínimos recursos adicionales.
When you open a realm for the first time, Realm performs the memory-mapping and schema validation required to read and write data to the realm. Additional instances of that realm on the same thread use the same underlying resources. Instances of that realm on separate threads use some of the same underlying resources.
Cuando todas las conexiones a un realm se cierran en un hilo, Realm libera los recursos del hilo utilizados para conectarse a ese realm. Cuando todas las conexiones a un realm se cierran en un proceso, Realm libera todos los recursos utilizados para conectarse a ese realm.
Como práctica recomendada, recomendamos vincular el ciclo de vida de la instancia de dominio con los ciclos de vida de las vistas que lo observan. Por ejemplo, considere RecyclerView que muestra datos RealmResults mediante un Fragment. Podrías:
Open a single realm that contains the data for that view in the
Fragment.onCreateView()lifecycle method.Cierra ese mismo realm en el método de ciclo de vida
Fragment.onDestroyView().
Nota
If your realm is especially large, fetching a realm instance in Fragment.onCreateView() may briefly block rendering. If opening your realm in onCreateView() causes performance issues, consider managing the realm from Fragment.onStart() and Fragment.onStop() instead.
Si varias instancias de Fragment requieren acceso al mismo conjunto de datos, puedes gestionar un único realm en el Activity que las contiene:
Open the realm in the
Activity.onCreate()lifecycle method.Close the realm in the
Activity.onDestroy()lifecycle method.
Multi-process
No se puede acceder simultáneamente a dominios cifrados o sincronizados desde diferentes procesos. Sin embargo, los dominios locales funcionan con normalidad entre procesos, por lo que se pueden leer, escribir y recibir notificaciones de varios APK.
Realm Schema
A Realm Schema is a list of valid object schemas that each define an object type that an App may persist. All objects in a realm must conform to the Realm Schema.
Por defecto, el SDK agrega automáticamente todas las clases de tu proyecto que deriven de RealmObject al esquema de realm.
Las aplicaciones cliente proveen un Esquema Realm al abrir un realm. Si un realm ya contiene datos, entonces Realm valida cada objeto existente para garantizar que se haya proporcionado un esquema de objeto para su tipo y que cumple con todas las restricciones especificadas en el esquema.
Ejemplo
Un realm que contiene información básica sobre libros en bibliotecas podría usar un esquema como el siguiente:
[ { "type": "Library", "properties": { "address": "string", "books": "Book[]" } }, { "type": "Book", "primaryKey": "isbn", "properties": { "isbn": "string", "title": "string", "author": "string", "numberOwned": { "type": "int?", "default": 0 }, "numberLoaned": { "type": "int?", "default": 0 } } } ]
Realms sincronizados
Una aplicación que utiliza Atlas Device Sync puede abrir un reino sincronizado.
Al usar Sincronización Flexible, puede personalizar los datos que sincroniza su aplicación cliente suscribiéndose a consultas. Estas consultas buscan datos en el backend de su aplicación, y el dominio de Sincronización Flexible sincroniza los datos que coinciden con ellas. La aplicación cliente solo puede sincronizar datos si el usuario tiene los permisos de lectura o de lectura y escritura adecuados para acceder a ellos.
Cuando utiliza Partition-Based Sync, los reinos sincronizados representan particiones de datos de Atlas. Cada realm corresponde a un subconjunto de los datos de la fuente de datos de tu aplicación. Puedes personalizar la particionamiento de datos usando la clave de partición de tu aplicación. Los valores únicos de la llave de partición, conocidos como valores de la partición, corresponden a reinos individuales.
You can customize permissions for the data that synced realms can read and write from your App when you configure Realm Rules.
Para obtener más información, consulta Configurar un Realm sincronizado - Java SDK.
Find Your Realm File
Realm stores a binary encoded version of every object and type in a realm in a single .realm file.
The filesystem used by Android emulators is not directly accessible from the machine running Realm Studio. You must download the file from the emulator before you can access it.
Primero, busca la ruta del archivo en el emulador:
// Run this on the device to find the path on the emulator Realm realm = Realm.getDefaultInstance(); Log.i("Realm", realm.getPath());
Then, download the file using ADB. You can do this while the app is running.
> adb pull <path>
You can also upload the modified file again using ADB, but only when the app isn't running. Uploading a modified file while the app is running can corrupt the file.
> adb push <file> <path>
Tip
Auxiliary Realm Files
Realm creates additional files for each realm. To learn more about these files, see Realm Internals.
Tamaño del archivo Realm
Realm usually takes up less space on disk than an equivalent SQLite database. However, in order to give you a consistent view of your data, Realm operates on multiple versions of a realm. If many versions of a realm are opened simultaneously, the realm file can require additional space on disk.
These versions take up an amount of space dependent on the amount of changes in each transaction. Many small transactions have the same overhead as a small number of large transactions.
El crecimiento inesperado del tamaño del archivo suele ocurrir por una de tres razones:
You open a realm on a background thread and forget to close it again. As a result, Realm retains a reference to the older version of data on the background thread. Because Realm automatically updates realms to the most recent version on threads with loopers, the UI thread and other Looper threads do not have this problem.
You hold references to too many versions of frozen objects. Frozen objects preserve the version of a realm that existed when the object was first frozen. If you need to freeze a large number of objects, consider using Realm.copyFromRealm() instead to only preserve the data you need.
You read some data from a realm. Then, you block the thread with a long-running operation. Meanwhile, you write many times to the realm on other threads. This causes Realm to create many intermediate versions. You can avoid this by:
batching the writes
avoiding leaving the realm open while otherwise blocking the background thread.
Limit the Maximum Number of Active Versions
You can set maxNumberOfActiveVersions() when building your RealmConfiguration to throw an IllegalStateException if your application opens more versions of a realm than the permitted number. Versions are created when executing a write transaction.
Realm automatically removes older versions of data once they are no longer used by your application. However, Realm does not free the space used by older versions of data; instead, that space is used for new writes to the realm.
Compactar un Realm
You can remove unused space by compacting the realm file:
Manualmente: llamar a compactRealm()
Automatically: specify the compactOnLaunch() builder option when opening the first connection to a realm in your Android application
Importante
Compactar todas las aplicaciones de producción
Every production application should implement compacting to periodically reduce realm file size.
Backup and Restore Realms
Realm guarda los realms en el disco utilizando archivos en tu dispositivo Android. Para realizar una copia de seguridad de un realm, busca tu archivo Realm y cópialo a un lugar seguro. Deberías cerrar todas las instancias del realm antes de copiarlo.
Alternativamente, también puedes usar realm.writeCopyTo() para escribir una versión compactada de un reino en un archivo de destino.
Modules
Los módulos Realm describen el conjunto de objetos Realm que se pueden almacenar en un Realm. Por defecto, Realm crea automáticamente un Módulo Realm que contiene todos los objetos Realm definidos en tu aplicación. Puede definir un RealmModule para restringir un Realm a un subconjunto de clases definidas en una aplicación. Si se desarrolla una librería que utiliza Realm, se puede usar un módulo Realm para incluir explícitamente solo los objetos Realm definidos en su librería en su realm. Esto permite que las aplicaciones que incluyen tu librería también puedan usar Realm sin gestionar conflictos de nombres de objetos ni migraciones con los objetos Realm definidos en tu librería.