Android WorkManager Return Result Parameters

Jun 11, 2019
Check Success or Failure Status
class DownloadPlaceWorker(context : Context, params : WorkerParameters) : Worker(context, params) {    companion object {        private const val WORK_NAME = "DownloadPlaceWorker"        private const val PARAM_PARENT_KEY = "parent_key"        const val RESULT_ITEM_ID = "itemt_id"        fun run(parentKey: String) : LiveData<WorkInfo> {            val data = workDataOf(PARAM_PARENT_KEY to parentKey)            val work = OneTimeWorkRequestBuilder<DownloadPlaceWorker>()                    .setInputData(data)                    .build()            WorkManager.getInstance().enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.KEEP, work)            return WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)        }    }    override fun doWork(): Result {        val parentKey = inputData.getString(PARAM_PARENT_KEY)        // do something        val itemId = 100        val output = Data.Builder()                .putInt(RESULT_ITEM_ID, itemId)                .build()        return Result.success(output)    }}

Receive return parameters/result

DownloadPlaceWorker.run(parentKey).observe(lifecycleOwner, Observer { info ->    if (info != null) {        if (info.state.isFinished) {            if (info.state == WorkInfo.State.SUCCEEDED) {                val itemId = info.outputData.getInt(DownloadPlaceWorker.RESULT_ITEM_ID, -1)                // do something            }            else if (info.state == WorkInfo.State.FAILED) {                // do something            }        }    }})

❤️ 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.