Android WorkManager Update Progress UI (Kotlin)

March 3, 2020
Use setProgress
class UploadPhotoWorker(context : Context, params : WorkerParameters) : CoroutineWorker(context, params)  {
    companion object {
        private const val WORK_NAME = "UploadPhotoWorker"
        const val PARAM_PROGRESS = "Progress"

        fun run(context: Context): LiveData<WorkInfo> {
            val work = OneTimeWorkRequestBuilder<UploadPhotoWorker>()
                .build()

            val manager = WorkManager.getInstance(context)
            manager.enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, work)
            return manager.getWorkInfoByIdLiveData(work.id)
        }

        fun stop(context: Context) {
            Timber.d("stop")
            val manager = WorkManager.getInstance(context)
            manager.cancelUniqueWork(WORK_NAME)
        }

        /*
        fun getWorkInfo(context: Context): LiveData<MutableList<WorkInfo>> {
            val manager = WorkManager.getInstance(context)

            return manager.getWorkInfosForUniqueWorkLiveData(WORK_NAME)
        }
         */
    }

    override suspend fun doWork(): Result {
        for (x in 1..100) {
            val progressData = workDataOf(PARAM_PROGRESS to x)
            setProgress(progressData)

            // do something
            try {
                delay(2000)
                // Thread.sleep(2000)
            } catch (e: CancellationException) {
                Timber.d("Cancelled")
            }


            if (isStopped) {
                Timber.d("isStopped")
                return Result.success(workDataOf(PARAM_PROGRESS to x))
            }
        }

        return Result.success(workDataOf(PARAM_PROGRESS to 100))
    }
}

Usage in Activity/Fragment

val liveData = UploadPhotoWorker.run(context)
liveData.observe(viewLifecycleOwner) {workInfo ->
    Timber.d("Running=${workInfo.state.isFinished}")
    val progress = workInfo.progress.getInt(UploadPhotoWorker.PARAM_PROGRESS, -1)
    Timber.d("Progress=$progress")
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.