Sync

object Sync

Entry point for initializing background data synchronization using WorkManager.

This object provides a simple API to start the background sync process that keeps local data synchronized with remote Firebase Firestore. The sync runs automatically when the app starts and can be triggered on-demand through SyncManager.

Sync Architecture

  • WorkManager: Handles background execution with constraints (network connectivity)

  • SyncWorker: Performs the actual sync logic (pull from Firestore, push to Firestore)

  • Foreground Service: Shows sync progress notification to the user

  • Exponential Backoff: Retries failed syncs up to 3 times with increasing delays

Initialization

Call initialize once from your Application's onCreate():

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Sync.initialize(this)
}
}

Sync Triggers

  1. App Startup: Automatically when initialize is called

  2. On-Demand: Via SyncManager.requestSync

  3. Periodic: Can be configured with WorkManager's PeriodicWorkRequest (not implemented by default)

Work Policy

Uses ExistingWorkPolicy.KEEP which means:

  • If sync is already running, new requests are ignored

  • If sync is pending, it won't be replaced

  • Only one sync runs at a time to prevent conflicts

Constraints

The sync worker only runs when:

  • Network is available (CONNECTED)

  • Battery is not critically low (handled by WorkManager)

Observing Sync State

Use SyncManager to observe when sync is running:

@HiltViewModel
class HomeViewModel @Inject constructor(
private val syncManager: SyncManager
) : ViewModel() {
val isSyncing: StateFlow<Boolean> = syncManager.isSyncing
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
}

See also

SyncManager

Functions

Link copied to clipboard
fun initialize(context: Context)

Initializes the sync process that keeps the app's data synchronized with Firestore.