Middle
Как вернуть результат работы WorkManager в приложение?
sobes.tech AI
Answer from AI
You can use Observer on a LiveData<WorkInfo> object or LiveData<List<WorkInfo>> obtained from WorkManager by id or tag. In WorkInfo, there is a field outputData that contains the result.
Example of obtaining LiveData:
// Getting LiveData by id
val workInfoByIdLiveData: LiveData<WorkInfo> =
WorkManager.getInstance(context).getWorkInfoByIdLiveData(workId)
// Getting LiveData by tag
val workInfoByTagLiveData: LiveData<List<WorkInfo>> =
WorkManager.getInstance(context).getWorkInfosByTagLiveData(tag)
Example of observing the result:
// Observing LiveData<WorkInfo>
workInfoByIdLiveData.observe(lifecycleOwner, Observer { workInfo ->
if (workInfo != null && workInfo.state.isFinished) {
val resultData = workInfo.outputData
// Process the result from resultData
}
})
Within Worker, the result is returned using Result.success(Data).
class MyWorker(appContext: Context, workerParams: WorkerParameters):
Worker(appContext, workerParams) {
override fun doWork(): Result {
// Perform background work
val outputData = Data.Builder()
.putString("result_key", "Success!")
.build()
return Result.success(outputData)
}
}