Android Shorts 🩳: WorkManager — Observing a WorkRequest (level paranoid)

Costa Fotiadis
Mar 31, 2023

Start a work request

(see how-to-hilt+workmanager in the previous episode)

A method in a ViewModel will do:

Observing the state

WorkManager.getWorkInfoByIdLiveData returns LiveData , which isn’t really useful at the moment.

Turn that into a flow by adding the livedata-ktx dependency.

Print out the state of the work request while you are at it.

Job done.

Or maybe..

The collection will be alive as long as the ViewModel is alive, patiently waiting for updates for a job that might be finished already.

Imagine starting a lot of work requests here. Clean up is in order.

supervisorScope?

Calling cancel() on the supervisorScope will cancel its job and all its children. Just about what is needed.

Log statements confirm this too:

The full method:

--

--