Esta página contiene información para usar Realm rápidamente con el SDK de Kotlin. El opcional La secciónAgregar sincronización de dispositivos ilustra cómo integrar Atlas Device Sync en su aplicación.
Antes de comenzar, asegúrate de haber instalado el SDK de Kotlin para tu plataforma.
Nota
Using this Quick Start with KMP
If you're running this project in a fresh Kotlin Multiplatform (KMP) template project, you can copy and paste the following snippets into the Greeting.greeting() method in the commonMain module.
Define tu modelo de objeto
Your application's data model defines the structure of data stored within Realm. You can define your application's data model via Kotlin classes in your application code with Realm Object Models.
Para definir el modelo de datos de tu aplicación, agrega una definición de clase a tu código de aplicación. El siguiente ejemplo ilustra la creación de un modelo "Item" que representa elementos de tareas pendientes en una aplicación de lista de tareas.
class Item() : RealmObject { var _id: ObjectId = ObjectId() var isComplete: Boolean = false var summary: String = "" var owner_id: String = "" constructor(ownerId: String = "") : this() { owner_id = ownerId } }
Abrir un reino
Usa RealmConfiguration.create() para abrir un reino con los parámetros predeterminados. Pasa tu configuración al constructor de la fábrica de reinos para generar una instancia de ese reino:
val config = RealmConfiguration.create(schema = setOf(Item::class)) val realm: Realm = Realm.open(config)
For more information on how to control the specifics of the RealmConfiguration you would like to open (e.g. name, location, schema version), refer to Open & Close a Realm.
Crear, leer, actualizar y eliminar objetos
Once opened, you can create objects within a realm in a write transaction block.
To create a new Item, instantiate an instance of the Item class and add it to the realm in a write transaction block:
realm.writeBlocking { copyToRealm(Item().apply { summary = "Do the laundry" isComplete = false }) }
You can retrieve a collection of all Todo items in the realm with query.find():
// all items in the realm val items: RealmResults<Item> = realm.query<Item>().find()
You can also filter a collection to retrieve a more specific collection of objects:
// items in the realm whose name begins with the letter 'D' val itemsThatBeginWIthD: RealmResults<Item> = realm.query<Item>("summary BEGINSWITH $0", "D") .find() // todo items that have not been completed yet val incompleteItems: RealmResults<Item> = realm.query<Item>("isComplete == false") .find()
Find more information about string Realm queries in Filter Data.
Para modificar un elemento de Todo, actualice sus propiedades en un bloque de transacción de escritura:
// change the first item with open status to complete to show that the todo item has been done realm.writeBlocking { findLatest(incompleteItems[0])?.isComplete = true }
Finally, you can delete a Todo item by calling mutableRealm.delete() in a write transaction block:
// delete the first item in the realm realm.writeBlocking { val writeTransactionItems = query<Item>().find() delete(writeTransactionItems.first()) }
Esté atento a los cambios
Puedes observar un reino, una colección o un objeto para detectar cambios con el observe .
Importante
Serverless Limitations
No puedes observar cambios si la fuente de datos es una instancia sin servidor de Atlas. El servidor sin servidor de MongoDB actualmente no admite flujos de cambios, que se emplean en las colecciones monitoreadas para escuchar cambios.
En el siguiente ejemplo, escuchamos cambios en todos los objetos Item.
// flow.collect() is blocking -- run it in a background context val job = CoroutineScope(Dispatchers.Default).launch { // create a Flow from the Item collection, then add a listener to the Flow val itemsFlow = items.asFlow() itemsFlow.collect { changes: ResultsChange<Item> -> when (changes) { // UpdatedResults means this change represents an update/insert/delete operation is UpdatedResults -> { changes.insertions // indexes of inserted objects changes.insertionRanges // ranges of inserted objects changes.changes // indexes of modified objects changes.changeRanges // ranges of modified objects changes.deletions // indexes of deleted objects changes.deletionRanges // ranges of deleted objects changes.list // the full collection of objects } else -> { // types other than UpdatedResults are not changes -- ignore them } } } }
Later, when you're done observing, cancel the job to cancel the coroutine:
job.cancel() // cancel the coroutine containing the listener
Close a Realm
Para cerrar un dominio y todos los recursos subyacentes, llame a realm.close().El close() método se bloquea hasta que se completen todas las transacciones de escritura en el dominio.
realm.close()
Agregar sincronización de dispositivos (opcional)
This section illustrates how to authenticate with an Anonymous User, and open a Flexible Sync realm to begin syncing data between devices.
Requisitos previos
The code snippets in this section require the following:
Se habilitó la autenticación anónima en la interfaz de usuario de App Services
Habilite la sincronización flexible con el modo de desarrollo activado y un
owner_idcampo en el Queryable Fields sección
Inicializar la aplicación
To use App Services features such as authentication and sync, access your App Services App using your App ID. You can find your App ID in the App Services UI.
val app = App.create(YOUR_APP_ID)
Authenticate a User
Para autenticar e iniciar sesión, llame a App.login. Cuando la autenticación anónima está habilitada, los usuarios pueden iniciar sesión inmediatamente en su aplicación sin proporcionar información de identificación.
val credentials = Credentials.anonymous() val user = app.login(credentials)
Open a Synced Realm
Once you have initialized your Atlas App Services App, authenticated a user, and defined your object model, you can create a SyncConfiguration.
Si ha abierto un reino local siguiendo la sección Abrir un reino anterior, reemplace RealmConfiguration con el que se SyncConfiguration describe a continuación.
Pass the authenticated user and the Item class to the SyncConfiguration.Builder function to create a Flexible Sync Configuration.
Importante
Initial Subscriptions
You need at least one subscription before you can read from or write to the realm. Use initialSubscriptions to define the initial subscription set when the Realm file is first opened. Pass the query you wish to subscribe to and a name for the subscription to the add() function.
The example below specifies a subscription named "User's Items" with all Item objects.
// create a SyncConfiguration val config = SyncConfiguration.Builder( user, setOf(Item::class) ) // the SyncConfiguration defaults to Flexible Sync, if a Partition is not specified .initialSubscriptions { realm -> add( realm.query<Item>( "owner_id == $0", // owner_id == the logged in user user.id ), "User's Items" ) } .build() val realm = Realm.open(config)
Next: Check out the Template Apps and Tutorial
Consulta la aplicación de plantilla para experimentar con otra forma rápida de empezar a programar con el SDK de Kotlin de Realm. La plantilla del SDK de Kotlin, etiquetada android.kotlin.todo.flex como, es una aplicación prediseñada que integra Realm y Atlas Device Sync en una aplicación Android personalizable.
Alternativamente, si está interesado en una experiencia guiada, puede leer nuestro tutorial de Android con Kotlin SDK que amplía la aplicación de plantilla.