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
/ /
Sync Device Data

Guardar datos en un Realm sincronizado - Kotlin SDK

Al escribir datos en un reino sincronizado usando Sincronización flexible: puedes usar las mismas API que al escribir en un dominio local. Sin embargo, hay algunas diferencias de comportamiento que debes tener en cuenta al desarrollar tu aplicación.

When you write to a synced realm, your write operations must match both of the following:

  • La query de suscripción de sincronización

  • The permissions in your App Services App

Si intentas escribir datos que no coinciden ni con la suscripción de query ni con los permisos del usuario, Realm revierte la escritura con una operación de error no fatal llamada escritura compensatoria.

To learn more about configuring permissions for your app, see Role-based Permissions and the Device Sync Permissions Guide in the App Services documentation.

Para obtener más información sobre errores permitidos denegados, errores de guardar compensatoria y otros tipos de errores de Device Sync, consulta Errores de sincronizar en la documentación de aplicación Services.

The data that you can write to a synced realm is determined by the following:

  • Your Device Sync configuration

  • Permisos en tu aplicación

  • La consulta de suscripción de sincronización flexible que se utiliza al abrir el reino

The examples on this page use an Atlas App Services App with the following Device Sync configuration and a client app with the following Realm SDK data model and subscriptions.

In this example, the client app uses the following object model:

class Item : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var ownerId: String = ""
var itemName: String = ""
var complexity: Int = 0
}

Based on the above example object model, Device Sync is configured with the following queryable fields:

  • _id (siempre incluido)

  • complexity

  • ownerId

The App Services App has permissions configured to let users read and write only their own data:

{
"roles": [
{
"name": "readOwnWriteOwn",
"apply_when": {},
"document_filters": {
"write": {
"ownerId": "%%user.id"
},
"read": {
"ownerId": "%%user.id"
}
},
"read": true,
"write": true,
"insert": true,
"delete": true,
"search": true
}
]
}

Cualquier objeto en la colección Atlas donde el ownerId no coincida con el user.id del usuario que inició sesión no se puede sincronizar con este reino.

Using the object model, the examples configure the synced realm to synchronize objects matching this subscription query:

val app = App.create(FLEXIBLE_APP_ID)
val user = app.login(credentials)
val flexSyncConfig = SyncConfiguration.Builder(user, setOf(Item::class))
// Add subscription
.initialSubscriptions { realm ->
add(
// Get Items from Atlas that match the Realm Query Language query.
// Uses the queryable field `complexity`.
// Query matches objects with complexity less than or equal to 4.
realm.query<Item>("complexity <= 4"),
"simple-items"
)
}
.build()
val syncRealm = Realm.open(flexSyncConfig)
syncRealm.subscriptions.waitForSynchronization()
Log.v("Successfully opened realm: ${syncRealm.configuration}")

Any object in the Atlas collection where the complexity property's value is greater than 4 cannot sync to this realm.

Writes to Flexible Sync realms may broadly fall into one of two categories, depending on whether the write matches the permissions and the Flexible Sync subscription query:

  • Successful writes: The written object matches both the query subscription and the user's permissions. The object writes successfully to the realm, and syncs successfully to the App Services backend and other devices.

  • Compensating writes: The written object does not match the subscription query or the user does not have sufficient permissions to perform the write. Realm reverts the illegal write with a compensating write operation.

Tip

If you want to write an object that does not match the query subscription, you can open a different realm where the object matches the query subscription. Alternately, you could write the object to a non-synced realm that does not enforce permissions or subscription queries.

Cuando el guardar coincide tanto con los permisos de usuario como con la suscripción de query en el cliente, el SDK de Realm Kotlin puede guardar correctamente el objeto en el realm sincronizado. Este objeto se sincroniza con el backend de aplicación Services cuando el dispositivo tiene una conexión de red.

// Per the Device Sync permissions, users can only read and write data
// where the `Item.ownerId` property matches their own user ID.
val userId = user.id
val newItem = Item().apply {
ownerId = userId
itemName = "This item meets sync criteria"
complexity = 3
}
syncRealm.write {
// `newItem` is successfully written to the realm and synced to Atlas
// because its data matches the subscription query (complexity <= 4)
// and its `ownerId` field matches the user ID.
copyToRealm(newItem)
}

Cuando la operación de guardar no coincide ni con la suscripción a la query ni con los permisos del usuario, Realm revierte la guardar y lanza una CompensatingWriteException.

In more detail, when you write data that is outside the bounds of a query subscription or does not match the user's permissions, the following occurs:

  1. Because the client realm has no concept of "illegal" writes, the write initially succeeds until Realm resolves the changeset with the App Services backend.

  2. Upon sync, the server applies the rules and permissions. The server determines that the user does not have authorization to perform the write.

  3. The server sends a revert operation, called a "compensating write", back to the client.

  4. The client's realm reverts the illegal write operation.

Any client-side writes to a given object between an illegal write to that object and the corresponding compensating write will be lost. In practice, this may look like the write succeeding, but then the object "disappears" when Realm syncs with the App Services backend and performs the compensating write.

When this occurs, you can refer to the App Services logs or use the CompensatingWriteInfo object in the client to get additional information on the error.

Dada la configuración para el Flexible Sync realm detallada arriba, intentar escribir este objeto resulta en un error de escritura compensatoria porque el objeto no coincide con la suscripción de query:

// The complexity of this item is `7`. This is outside the bounds
// of the subscription query, which triggers a compensating write.
val itemTooComplex = Item().apply {
ownerId = user.id
itemName = "This item is too complex"
complexity = 7
}
syncRealm.write {
copyToRealm(itemTooComplex)
}
[Session][CompensatingWrite(231)] Client attempted a write that is disallowed by permissions, or modifies an object outside the current query, and the server undid the change.

Verá el siguiente mensaje de error en los registros de App Services:

Error:
Client attempted a write that is outside of permissions or query filters; it has been reverted (ProtocolErrorCode=231)
Details:
{
"Item": {
"63bdfc40f16be7b1e8c7e4b7": "write to \"63bdfc40f16be7b1e8c7e4b7\"
in table \"Item\" not allowed; object is outside of
the current query view"
}
}

Dados los permisos en la configuración de Device Sync detallada anteriormente, intentar guardar este objeto resulta en un error de escritura compensatoria porque la propiedad ownerId no coincide con la user.id del usuario que ha iniciado sesión:

// The `ownerId` of this item does not match the `user.id` of the logged-in
// user. The user does not have permissions to make this write, which
// triggers a compensating write.
val itemWithWrongOwner = Item().apply {
ownerId = "not the current user"
itemName = "A simple item"
complexity = 1
}
syncRealm.write {
copyToRealm(itemWithWrongOwner)
}
[Session][CompensatingWrite(231)] Client attempted a write that is disallowed by permissions, or modifies an object outside the current query, and the server undid the change.

Verá el siguiente mensaje de error en los registros de App Services:

Error:
Client attempted a write that is outside of permissions or query filters; it has been reverted (ProtocolErrorCode=231)
Details:
{
"Item": {
"63bdfc40f16be7b1e8c7e4b7": "write to \"63bdfc40f16be7b1e8c7e4b7\"
in table \"Item\" was denied by write filter in role \"readOwnWriteOwn\""
}
}

Nueva en la versión 1.9.0.

Puede obtener información adicional en el cliente sobre por qué se produce una escritura compensatoria utilizando el objeto CompensatingWriteInfo, que proporciona:

  • El objectType del objeto que el cliente intentó escribir

  • The primaryKey of the specific object

  • The reason for the compensating write error

Esta información es la misma que se encuentra en los registros de App Services. El SDK de Kotlin expone este objeto en el cliente para mayor comodidad y para la depuración.

A continuación, se muestra un ejemplo de cómo podrías registrar información sobre errores de escritura compensatorios:

val syncErrorHandler = SyncSession.ErrorHandler { session, error ->
runBlocking {
if (error is CompensatingWriteException) {
error.writes.forEach { writeInfo ->
val errorMessage = """
A write was rejected with a compensating write error
The write to object type: ${writeInfo.objectType}
With primary key of: ${writeInfo.primaryKey}
Was rejected because: ${writeInfo.reason}
""".trimIndent()
Log.e(errorMessage)
}
}
}
}
A write was rejected with a compensating write error
The write to object type: Item
With primary key of: RealmAny{type=OBJECT_ID, value=BsonObjectId(649f2c38835cc0346b861b74)}
Was rejected because: write to "649f2c38835cc0346b861b74" in table "Item" not allowed; object is outside of the current query view
  • El Item en este mensaje es el Item objeto utilizado en el modelo de objetos de esta página.

  • The primary key is the objectId of the specific object the client attempted to write.

  • The table "Item" refers to the Atlas collection where this object would sync.

  • The reason object is outside of the current query view in this example is because the query subscription was set to require the object's complexity property to be less than or equal to 4, and the client attempted to write an object outside of this boundary.

Every write transaction for a subscription set has a performance cost. If you need to make multiple updates to a Realm object during a session, consider keeping edited objects in memory until all changes are complete. This improves sync performance by only writing the complete and updated object to your realm instead of every change.

Volver

Gestionar suscripciones

En esta página