Skip to content

Instantly share code, notes, and snippets.

@akueisara
Forked from ceruleanotter/SimpleWorkStatusObservation.kt
Last active June 26, 2022 16:29
Show Gist options
  • Save akueisara/037d2a6fb86fa1b6c3a29119927989c0 to your computer and use it in GitHub Desktop.
Save akueisara/037d2a6fb86fa1b6c3a29119927989c0 to your computer and use it in GitHub Desktop.
WorkManager Basics: WorkStatus Observation
WorkManager.getInstance().cancelWorkById(uploadWorkRequest.id)
WorkManager.getInstance().cancelAllWorkByTag("sometag")
// In your UI (activity, fragment, etc)
// Each WorkRequest has a unique id and that unique id is one way to look up the associated WorkInfo.
WorkManager.getInstance().getWorkInfoByIdLiveData(uploadWorkRequest.id)
// The ability to observe and be notified when the WorkInfo changes is a feature provided by LiveData.
.observe(lifecycleOwner, Observer { workInfo ->
// Check if the current work's state is "successfully finished"
if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
displayImage(workInfo.outputData.getString(KEY_IMAGE_URI))
}
})
// Observe by tag, which is something associated with the WorkRequest(s)
WorkManager.getInstance().getWorkInfoByTagLiveData("sometag")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment