I can't understand why the WorkManager
runs the Worker
twice, not always just one of the many runs.
For example, method enqueueWorkers
receives an array with one element and enqueues it as a OneTimeWorkerRequest
without any backoff policies. Even if array have many items, each unique with trigger id from database. The doWork()
method executes successfully, without any exceptions. Why success? Because inside executor.waitFinish
writes logs to database with default behaviour and expected end. However, in the background inspector from Android Studio, I see that the run count is 2 and the retries are 1. As I understand this is not a duplicate request, it is a re-run of the same.
Does the WorkManager
catch any exceptions behind me? Or what the reason retry successful work?
private fun enqueueProgramWorkers(triggers: List<QueueDateTriggerModel>) {
if (triggers.isEmpty()) {
return
}
val triggerRequests = triggers.map {
val tag = createTriggerTag(it.trigger.id)
workManager.cancelAllWorkByTag(tag)
OneTimeWorkRequestBuilder<ProgramWorker>()
.setInputData(ProgramWorker.workDataOf(it.trigger.programId, EnqueueSource.DATE_TRIGGER, it.trigger.id))
.setInitialDelay(it.delayToLaunch, TimeUnit.MILLISECONDS)
.addTag(tag)
.build()
}
workManager.enqueue(triggerRequests)
}
@HiltWorker
class ProgramWorker @AssistedInject constructor(
@Assisted private val context: Context,
@Assisted params: WorkerParameters,
private val executor: Executor,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = withContext(ioScope.coroutineContext) {
val model = ProgramWorkerModel(inputData)
setForeground()
executor.waitFinish(model.programId)
return@withContext Result.success()
}
suspend fun setForeground() {
try {
setForeground(getForegroundInfo())
} catch (error: IllegalStateException) {
Log.d("ProgramWorker ", error.message.toString())
}
}
companion object {
fun workDataOf(programId: Int, enqueueSource: EnqueueSource, triggerId: Int = NEW_ID): Data {
return workDataOf(
PROGRAM_ID to programId,
ENQUEUE_SOURCE to enqueueSource.name,
TRIGGER_ID to triggerId
)
}
}
}
implementation "androidx.work:work-runtime-ktx:2.10.0"