Reputation: 5378
My current Android application employs
archWorkerRuntimeVersion = '2.3.0-beta02'
api "androidx.work:work-runtime:$archWorkerRuntimeVersion"
api "androidx.work:work-runtime-ktx:$archWorkerRuntimeVersion"
I am observing the workers state via LiveData as follows:-
WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(myWorkRequest.id).observe(lifeCycleOwner, Observer {
if (it != null && it.state == WorkInfo.State.ENQUEUED) {
// DO SOMETHING IMPORTANT
}
})
Can I rely on always observing a state of WorkInfo.State.ENQUEUED
?
or could my observer not be presented with this state in some circumstances?
Upvotes: 0
Views: 1067
Reputation: 992
Yes, it is guaranteed to observe though there few things that you have to keep on mind related to this API. Below is description is from google:
* Adds the given observer to the observers list. This call is similar to
* {@link LiveData#observe(LifecycleOwner, Observer)} with a LifecycleOwner, which
* is always active. This means that the given observer will receive all events and will never
* be automatically removed. You should manually call {@link #removeObserver(Observer)} to stop
* observing this LiveData.
* While LiveData has one of such observers, it will be considered
* as active.
* <p>
* If the observer was already added with an owner to this LiveData, LiveData throws an
* {@link IllegalArgumentException}.
And below observe code should be called from Main thread otherwise the status will not be latest
WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(myWorkRequest.id).observe(lifeCycleOwner, Observer {
if (it != null && it.state == WorkInfo.State.ENQUEUED) {
// DO SOMETHING IMPORTANT
}
})
Upvotes: 1