Android WorkManager Update Progress UI (Kotlin)

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")}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.