Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
io.realm.mongodb.sync

Class SyncConfiguration.Builder

java.lang.Object
io.realm.mongodb.sync.SyncConfiguration.Builder

Enclosing class:

SyncConfiguration

Builder used to construct instances of a SyncConfiguration in a fluent manner.

Constructor and Description
User user
)

Crea una instancia del generador para una SyncConfiguration de Flexible Sync con el usuario dado.

User user,
String partitionValue
)

Crea una instancia del generador para una sincronización basada en partición SyncConfiguration con el usuario y el valor de partición indicados.

User user,
ObjectId partitionValue
)

Crea una instancia del generador para una sincronización basada en partición SyncConfiguration con el usuario y el valor de partición indicados.

Modificador y Tipo
Método y descripción
Object module
)

Agrega un módulo a los módulos ya definidos.

boolean allowQueriesOnUiThread
)

Establece si o no RealmQueries Se permiten desde el hilo de UI.

boolean allowWritesOnUiThread
)

Sets whether or not calls to Realm.executeTransaction are allowed from the UI thread.

String assetFile
)

When opening the Realm for the first time, instead of creating an empty file, the Realm file will be copied from the provided asset file and used instead.

Crea la RealmConfiguration basada en los parámetros del generador.

Sets the handler for when a Client Reset occurs.

Sets this to determine if the Realm file should be compacted before returned to the user.

Si estableces esta opción, Realm compactará el archivo Realm si este ha crecido demasiado y se puede recuperar una cantidad significativa de espacio.

byte[] key
)

Establece la clave de bytes io.realm.Realm#ENCRYPTION_KEY_LENGTH utilizada para cifrar y descifrar el archivo Realm.

Sets the error handler used by this configuration.

Establece la FlowFactory utilizada para crear flujos de corrutinas a partir de objetos Realm.

Establecer esto creará un Realm en memoria en lugar de guardarlo en el disco.

Sets the initial data in io.realm.Realm .

Establece el número máximo de versiones activas en el archivo Realm antes de que se lance una IllegalStateException al intentar guardar más datos.

Replaces the existing module(s) with one or more RealmModule s.

Object baseModule,
java.lang.Object[] additionalModules
)

Replaces the existing module(s) with one or more RealmModule s.

String filename
)

Sets the filename for the Realm file on this device.

Configurar esto hará que el Realm se vuelva de solo lectura y todas las transacciones de escritura realizadas contra este Realm fallarán con una IllegalStateException .

Sets the RxObservableFactory used to create Rx Observables from Realm objects.

long schemaVersion
)

Establece la versión de esquema del Realm.

Sets the handler for when a Client Reset occurs.

Sets the handler for when a Client Reset occurs.

String urlPrefix
)

The prefix that is prepended to the path in the WebSocket request that initiates a sync connection to MongoDB Realm.

Al configurar esto, el Realm descargará todos los cambios conocidos desde el servidor la primera vez que se abra un Realm.

Al configurar esto, el Realm descargará todos los cambios conocidos desde el servidor la primera vez que se abra un Realm.

  • Methods inherited from class java.lang.Object : getClass , hashCode , equals , clone , toString , notify , notifyAll , wait , wait , wait , finalize

public Builder (
User user
)

Crea una instancia del generador para una SyncConfiguration de Flexible Sync con el usuario dado.

Parámetros

  • user - The user that will be used for accessing the Realm App.

Tip

  • {@link SubscriptionSet} for more information about Flexible Sync.

public Builder (
User user,
String partitionValue
)

Crea una instancia del generador para una sincronización basada en partición SyncConfiguration con el usuario y el valor de partición indicados.

Parámetros

  • user - The user that will be used for accessing the Realm App.

  • partitionValue - The partition value identifying the remote Realm that will be synchronized.

public Builder (
User user,
ObjectId partitionValue
)

Crea una instancia del generador para una sincronización basada en partición SyncConfiguration con el usuario y el valor de partición indicados.

Parámetros

  • user - The user that will be used for accessing the Realm App.

  • partitionValue - The partition value identifying the remote Realm that will be synchronized.

Agrega un módulo a los módulos ya definidos.

boolean allowQueriesOnUiThread
)

Sets whether or not RealmQueries are allowed from the UI thread.

By default Realm allows queries on the main thread. However, by doing so your application may experience a drop of frames or even ANRs. We recommend diverting queries to non-UI threads or, alternatively, using RealmQuery.findAllAsync() or RealmQuery.findFirstAsync() .

boolean allowWritesOnUiThread
)

Sets whether or not calls to Realm.executeTransaction are allowed from the UI thread.

WARNING: Realm does not allow synchronous transactions to be run on the main thread unless users explicitly opt in with this method. We recommend diverting calls to executeTransaction to non-UI threads or, alternatively, using Realm.executeTransactionAsync .

Al abrir un Realm por primera vez, en lugar de crear un archivo vacío, el archivo Realm se copiará del archivo de recursos proporcionado y se usará en su lugar. Esto puede usarse para pre-poblar el Realm con datos, para que no sea necesario descargarlos del servidor.

El archivo Realm proporcionado debe ser un Realm sincronizado válido para el usuario dado y debe haber sido creado utilizando la API Realm.writeCopyTo(File).

ADVERTENCIA: Esto podría ser una operación prolongada y, lo ideal, es realizarla en un hilo en segundo plano.

Parámetros

  • assetFile - path to the asset database file.

Throws

Crea la RealmConfiguration basada en los parámetros del generador.

Devuelve

el SyncConfiguration creado.

Throws

Sets the handler for when a Client Reset occurs. If no handler is set, and error is logged when a Client Reset occurs.

Parámetros

  • handler - custom handler in case of a Client Reset.

Sets this to determine if the Realm file should be compacted before returned to the user. It is passed the total file size (data + free space) and the bytes used by data in the file.

Parámetros

  • compactOnLaunch - a callback called when opening a Realm for the first time during the life of a process to determine if it should be compacted before being returned to the user. It is passed the total file size (data + free space) and the bytes used by data in the file.

Setting this will cause Realm to compact the Realm file if the Realm file has grown too large and a significant amount of space can be recovered. See DefaultCompactOnLaunchCallback for details.

Establece la clave de bytes io.realm.Realm#ENCRYPTION_KEY_LENGTH utilizada para cifrar y descifrar el archivo Realm.

Parámetros

  • key - the encryption key.

Throws

Establece el gestor de errores utilizado por esta configuración. Solo los errores que no sean manejados por el SyncPolicy definido serán reportados a este gestor de errores.

Parámetros

  • errorHandler - gestor de errores utilizado para informar errores al comunicarse con el objeto Realm Server.

Throws

Sets the FlowFactory used to create coroutines Flows from Realm objects. The default factory is RealmFlowFactory .

Parámetros

  • factory - fábrica a utilizar.

Setting this will create an in-memory Realm instead of saving it to disk. In-memory Realms might still use disk space if memory is running low, but all files created by an in-memory Realm will be deleted when the Realm is closed.Note that because in-memory Realms are not persisted, you must be sure to hold on to at least one non-closed reference to the in-memory Realm object with the specific name as long as you want the data to last.

Establece los datos iniciales en io.realm.Realm. Esta transacción se ejecutará solo la primera vez que se abra (cree) el archivo Realm o durante la migración de datos si se ha definido RealmConfiguration.Builder.deleteRealmIfMigrationNeeded().

Parámetros

  • transaction - transaction to execute.

Sets the initial Subscription s for the io.realm.Realm . This will only be executed the first time the Realm file is opened (and the file created). If waitForInitialRemoteData() is configured as well, the realm file isn't fully opened until all subscription data also has been uploaded.

Parámetros

Establece el número máximo de versiones activas en el archivo Realm antes de que se lance una IllegalStateException al intentar guardar más datos.

Realm is capable of concurrently handling many different versions of Realm objects. This can happen if you have a Realm open on many different threads or are freezing objects while data is being written to the file.

Under normal circumstances this is not a problem, but if the number of active versions grow too large, it will have a negative effect on the filesize on disk. Setting this parameters can therefore be used to prevent uses of Realm that can result in very large Realms.

Note, the version number will also increase when changes from other devices are integrated on this device, so the number of active versions will also depend on what other devices writing to the same Realm are doing.

Parámetros

  • number - the maximum number of active versions before an exception is thrown.

Tip

Replaces the existing module(s) with one or more RealmModule s. Using this method will replace the current schema for this Realm with the schema defined by the provided modules.

A reference to the default Realm module containing all Realm classes in the project (but not dependencies), can be found using Realm.getDefaultModule() . Combining the schema from the app project and a library dependency is thus done using the following code:

builder.modules(Realm.getDefaultMode(), new MyLibraryModule());

Parámetros

  • modules - list of modules tthe first Realm module (required).

Throws

Object baseModule,
java.lang.Object[] additionalModules
)

Replaces the existing module(s) with one or more RealmModule s. Using this method will replace the current schema for this Realm with the schema defined by the provided modules.

A reference to the default Realm module containing all Realm classes in the project (but not dependencies), can be found using Realm.getDefaultModule() . Combining the schema from the app project and a library dependency is thus done using the following code:

builder.modules(Realm.getDefaultMode(), new MyLibraryModule());

Parámetros

  • baseModule - el primer módulo de Realm (obligatorio).

  • additionalModules - los módulos adicionales de Realm

Throws

Sets the filename for the Realm file on this device.

Parámetros

  • filename - name for the Realm file.

Configurar esto hará que el Realm se vuelva de solo lectura y todas las transacciones de escritura realizadas contra este Realm fallarán con una IllegalStateException .

This in particular mean that initialData(Realm.Transaction) will not work in combination with a read only Realm and setting this will result in a IllegalStateException being thrown.

Marking a Realm as read only only applies to the Realm in this process. Other processes and devices can still write to the Realm.

Establece la RxObservableFactory que se usa para crear Rx Observables a partir de objetos Realm. La fábrica por defecto es RealmObservableFactory .

Parámetros

  • factory - fábrica a utilizar.

long schemaVersion
)

Establece la versión del esquema de Realm. Solo los Realms sincronizados admiten cambios aditivos en el esquema que pueden aplicarse sin requerir una migración manual. La versión del esquema solo se utilizará como una indicación para la capa de almacenamiento subyacente para remover o agregar índices. Estos serán recalculados si la versión del esquema proporcionada difiere de la versión en el archivo Realm. ADVERTENCIA: No se garantiza que el valor insertado aquí sea el mismo que retorna Realm.getVersion(). Debido a la naturaleza de los Realms sincronizados, el valor tanto puede ser superior como inferior.

  • Será menor si otro cliente con un schemaVersion menor se conecta al servidor por primera vez después de que se utilizó esta schemaVersion.

  • Será mayor si otro cliente con un schemaVersion más alto se conecta al servidor después de la creación de este Realm.

Parámetros

  • schemaVersion - the schema version.

Throws

Sets the handler for when a Client Reset occurs. If no handler is set, and error is logged when a Client Reset occurs. This strategy is only available for synced realms using partition based sync. Realms using flexible sync currently only support syncClientResetStrategy(ManuallyRecoverUnsyncedChangesStrategy) .

Parámetros

  • handler - custom seamless loss handler in case of a Client Reset.

Sets the handler for when a Client Reset occurs. If no handler is set, and error is logged when a Client Reset occurs.

Parámetros

  • handler - custom manual handler in case of a Client Reset.

The prefix that is prepended to the path in the WebSocket request that initiates a sync connection to MongoDB Realm. The value specified must match the server’s configuration otherwise the device will not be able to create a connection. This value is optional and should only be set if a specific firewall rule requires it.

Parámetros

  • urlPrefix - The prefix to append to the sync connection url.

Al configurar esto, Realm descargará todos los cambios conocidos del servidor la primera vez que se abra. Realm no se abrirá hasta que se hayan descargado todos los datos. Esto significa que, si un dispositivo está sin conexión, Realm no se abrirá. Dado que descargar todos los cambios puede ser una operación larga que podría bloquear el hilo de la interfaz de usuario, los Realms con esta configuración habilitada solo deben abrirse en hilos en segundo plano o con Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) en el hilo de la interfaz de usuario.

This check is only enforced the first time a Realm is created. If you otherwise want to make sure a Realm has the latest changes, use SyncSession.downloadAllServerChanges() .

Parámetros

Al configurar esto, Realm descargará todos los cambios conocidos del servidor la primera vez que se abra. Realm no se abrirá hasta que se hayan descargado todos los datos. Esto significa que, si un dispositivo está sin conexión, Realm no se abrirá. Dado que descargar todos los cambios puede ser una operación larga que podría bloquear el hilo de la interfaz de usuario, los Realms con esta configuración habilitada solo deben abrirse en hilos en segundo plano o con Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) en el hilo de la interfaz de usuario.

This check is only enforced the first time a Realm is created. If you otherwise want to make sure a Realm has the latest changes, use SyncSession.downloadAllServerChanges() .

Volver

SyncConfiguration