Android WorkManager Return Result Parameters

June 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
            }
        }
    }
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.