|
|
|
@ -17,31 +17,14 @@
|
|
|
|
|
package com.google.samples.apps.nowinandroid.sync.initializers
|
|
|
|
|
|
|
|
|
|
import android.content.Context
|
|
|
|
|
import androidx.startup.AppInitializer
|
|
|
|
|
import androidx.startup.Initializer
|
|
|
|
|
import androidx.work.ExistingWorkPolicy
|
|
|
|
|
import androidx.work.WorkManager
|
|
|
|
|
import androidx.work.WorkManagerInitializer
|
|
|
|
|
import com.google.samples.apps.nowinandroid.sync.workers.SyncWorker
|
|
|
|
|
|
|
|
|
|
object Sync {
|
|
|
|
|
// This method is a workaround to manually initialize the sync process instead of relying on
|
|
|
|
|
// automatic initialization with Androidx Startup. It is called from the app module's
|
|
|
|
|
// Application.onCreate() and should be only done once.
|
|
|
|
|
// This method is initializes sync, the process that keeps the app's data current.
|
|
|
|
|
// It is called from the app module's Application.onCreate() and should be only done once.
|
|
|
|
|
fun initialize(context: Context) {
|
|
|
|
|
AppInitializer.getInstance(context)
|
|
|
|
|
.initializeComponent(SyncInitializer::class.java)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// This name should not be changed otherwise the app may have concurrent sync requests running
|
|
|
|
|
internal const val SyncWorkName = "SyncWorkName"
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Registers work to sync the data layer periodically on app startup.
|
|
|
|
|
*/
|
|
|
|
|
class SyncInitializer : Initializer<Sync> {
|
|
|
|
|
override fun create(context: Context): Sync {
|
|
|
|
|
WorkManager.getInstance(context).apply {
|
|
|
|
|
// Run sync on app startup and ensure only one sync worker runs at any time
|
|
|
|
|
enqueueUniqueWork(
|
|
|
|
@ -50,10 +33,8 @@ class SyncInitializer : Initializer<Sync> {
|
|
|
|
|
SyncWorker.startUpSyncWork(),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Sync
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
override fun dependencies(): List<Class<out Initializer<*>>> =
|
|
|
|
|
listOf(WorkManagerInitializer::class.java)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// This name should not be changed otherwise the app may have concurrent sync requests running
|
|
|
|
|
internal const val SyncWorkName = "SyncWorkName"
|
|
|
|
|