Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Sync Device Data

Sync Data in the Background - Kotlin SDK

Si necesitas sincronizar datos cuando la aplicación no se esté ejecutando, puedes sincronizar los reinos en un proceso en segundo plano.

To get started with background synchronization, you need to add the following dependencies to your Android application:

  • androidx.work:tiempo de ejecución del trabajo para poner trabajos en cola

  • androidx.concurrent:concurrent-futures to return job results from a background worker

La sincronización en segundo plano requiere dos cosas:

  • Lógica de sincronización

  • A scheduled job that periodically performs the sync logic

First, write the custom logic that synchronizes your realm. Treat this logic as a standalone connection to your backend. As a result, you'll need to:

  1. Obtenga la configuración de sincronización de Realm para su aplicación

  2. Autentica a un usuario para abrir el realm. Puedes usar las credenciales en caché de un usuario para un usuario que haya iniciado sesión y cuyo token de actualización no haya expirado.

  3. Abra el dominio y use SyncSession.downloadAllServerChanges() y SyncSession.uploadAllLocalChanges() para sincronizarlo completamente con el backend. Para más información,consulte Administrar sesiones de sincronización.

  4. Close the realm.

Puedes ejecutar esta lógica como un proceso en segundo plano usando una subclase de CoroutineWorker. Coloca tu lógica de sincronización en el doWork() método de su trabajador.

Example RealmBackgroundWorker.kt
package com.mongodb.app.worker
import android.annotation.SuppressLint
import android.content.Context
import androidx.concurrent.futures.ResolvableFuture
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.mongodb.app.app
import com.mongodb.app.data.RealmSyncRepository
import io.realm.kotlin.Realm
import io.realm.kotlin.mongodb.syncSession
class RealmBackgroundWorker(context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
private lateinit var future: ResolvableFuture<Result>
@SuppressLint("RestrictedApi")
override suspend fun doWork(): Result {
future = ResolvableFuture.create()
// Get the realm configuration for your app
val syncRepository = RealmSyncRepository { session, error ->
future.setException(error)
}
val config = syncRepository.getRealmConfiguration()
// Check if user is logged-in
if (app.currentUser?.loggedIn == true) {
val realm = Realm.open(config)
try {
realm.syncSession.downloadAllServerChanges()
realm.syncSession.uploadAllLocalChanges()
} catch (e: InterruptedException) {
e.printStackTrace()
} finally {
realm.close()
}
return future.get()
}
companion object {
const val UNIQUE_WORK_NAME = "RealmBackgroundWorker"
}
}

To create a worker that periodically performs background sync:

  1. Create a set of Constraints that specify the conditions required for your worker. Because synchronizing a realm uses data, you should consider only downloading changes in the background when the device is not:

    • Batería baja

    • Using a metered data source

  2. Especifica con qué frecuencia debe ejecutarse tu trabajador. Tu intervalo de repetición depende de la frecuencia con la que se actualicen los datos en el realm y con la frecuencia que los usuarios abran tu aplicación:

    • If the realm frequently updates throughout the day, consider setting a repeat interval of 1-3 hours.

    • If the realm only updates a small number of times each day, it's best to set a less frequent repeat interval and only background sync once or twice a day.

  3. Enqueue your worker with the Android OS. Assign it a unique identifier so that you can update the job in the future.

Tip

You can create the background sync job inside an Application subclass in your app to guarantee that the logic only executes once every time your application runs.

Ejemplo de trabajador
// Define any constraints for the background job
val constraints: Constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresBatteryNotLow(true)
.build()
// Define the frequency of the background job
val backgroundRealmSync =
PeriodicWorkRequestBuilder<RealmBackgroundWorker>(
// Repeat every 12 hours
12, TimeUnit.HOURS,
// Execute job at any point during that 12-hour period
12, TimeUnit.HOURS
)
.setConstraints(constraints)
.build()
// Enqueue the work job, replacing it with the most recent
// version if we update it
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
RealmBackgroundWorker.UNIQUE_WORK_NAME,
ExistingPeriodicWorkPolicy.UPDATE,
backgroundRealmSync
)

Volver

Stream Data to Atlas

En esta página