Skip to content

Instantly share code, notes, and snippets.

@maxirosson
Last active March 24, 2021 18:16
Show Gist options
  • Save maxirosson/1c2b278c101c606937e0fc723c38ce68 to your computer and use it in GitHub Desktop.
Save maxirosson/1c2b278c101c606937e0fc723c38ce68 to your computer and use it in GitHub Desktop.
RemoteConfigFetcherWorker
class RemoteConfigFetcherWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
companion object {
fun enqueue(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workRequestBuilder = OneTimeWorkRequestBuilder<RemoteConfigFetcherWorker>().setConstraints(constraints)
WorkManager.getInstance(context).enqueueUniqueWork(
RemoteConfigFetcherWorker::class.java.simpleName,
ExistingWorkPolicy.KEEP, workRequestBuilder.build()
)
}
}
override fun onWork(): Result {
return try {
// Block on the task for a maximum of 60 seconds, otherwise time out.
val taskResult = Tasks.await(Firebase.remoteConfig.fetchAndActivate(), 60, TimeUnit.SECONDS)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
sharedPreferences.edit().putBoolean("remote_config_stale", false).apply()
return Result.success()
} catch (e: ExecutionException) {
// The Task failed, this is the same exception you'd get in a non-blocking failure handler.
return if (e.cause is FirebaseRemoteConfigClientException && e.cause?.cause is IOException) {
Result.retry()
} else {
// TODO Log the error here
Result.failure()
}
} catch (e: InterruptedException) {
// An interrupt occurred while waiting for the task to complete.
return Result.retry()
} catch (e: TimeoutException) {
// Task timed out before it could complete.
return Result.retry()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment