Junior — Middle
How can you extract and process the result of task execution using WorkManager?
sobes.tech AI
Answer from AI
To extract and process the result of task execution in WorkManager, the WorkInfo object is used, which can be obtained via WorkManager.getWorkInfoByIdLiveData() or WorkManager.getWorkInfoById(). The WorkInfo contains the task status and result data (outputData).
Example of usage with LiveData:
val workRequest = OneTimeWorkRequestBuilder<MyWorker>().build()
WorkManager.getInstance(context).enqueue(workRequest)
WorkManager.getInstance(context).getWorkInfoByIdLiveData(workRequest.id)
.observe(lifecycleOwner) { workInfo ->
if (workInfo != null && workInfo.state.isFinished) {
val output = workInfo.outputData.getString("result_key")
// Process the result
}
}
Thus, you can subscribe to task status changes and get the result after its completion.