Sunday 12 January 2020

How to observe last emitted WorkManager getWorkInfoByIdLiveData with Android Worker

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 worker state via LiveData as follows:-

 WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(experimentRequest.id).observe(lifeCycleOwner, observer)

where lifeCycleOwner is my Activity and observer is a static val

private val observer = object : Observer<WorkInfo> {
    override fun onChanged(it: WorkInfo?) {
        Log.e("Worker", "this is our single observer $it $this")
        if (it == null) return
        repository.storeCurrentWorkId(it.id)
    }
}

the comment for observe(lifeCycleOwner, observer) states:-

/**
 * Adds the given observer to the observers list within the lifespan of the given
 * owner. The events are dispatched on the main thread. If LiveData already has data
 * set, it will be delivered to the observer.
 * <p>
 * The observer will only receive events if the owner is in {@link Lifecycle.State#STARTED}
 * or {@link Lifecycle.State#RESUMED} state (active).
 * <p>
 * If the owner moves to the {@link Lifecycle.State#DESTROYED} state, the observer will
 * automatically be removed.
 * <p>
 * When data changes while the {@code owner} is not active, it will not receive any updates.
 * If it becomes active again, it will receive the last available data automatically.
 * <p>
 * LiveData keeps a strong reference to the observer and the owner as long as the
 * given LifecycleOwner is not destroyed. When it is destroyed, LiveData removes references to
 * the observer &amp; the owner.
 * <p>
 * If the given owner is already in {@link Lifecycle.State#DESTROYED} state, LiveData
 * ignores the call.
 * <p>
 * If the given owner, observer tuple is already in the list, the call is ignored.
 * If the observer is already in the list with another owner, LiveData throws an
 * {@link IllegalArgumentException}.
 *
 * @param owner    The LifecycleOwner which controls the observer
 * @param observer The observer that will receive the events
 */

this statement does not appear to hold true though

If it becomes active again, it will receive the last available data automatically.

Unless I am misinterpreting it's meaning.

I took this to mean that when my activity become active again I would receive the latest (last) available data.

from my testing this is not the case, the only data I receive is any new data that is sent AFTER my activity becomes active again.

What am I doing wrong?

Is there any way to receive the latest data when my activity becomes active?



from How to observe last emitted WorkManager getWorkInfoByIdLiveData with Android Worker

No comments:

Post a Comment