Search code examples
androidandroid-studiokotlinandroid-workmanager

workstatus observer always in enqueued state


I am trying to observe my workers but they are always in queued state or sometime it's RUNNING but never SUCCEED or FAILED.

is workStatus.state from return in doWork() or it's different?

this is my worker script:

package com.mockie.daikokuten.sync.workers

import androidx.work.Worker


class TestWorker:Worker()
{

override fun doWork():Worker.Result
{
    return Worker.Result.SUCCESS
}

}

this is script to observe the workers :

 val test = PeriodicWorkRequest.Builder(
            TestWorker::class.java,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS)
            .addTag("test_worker")
            .build()

    WorkManager.getInstance()?.enqueueUniquePeriodicWork("test_worker", ExistingPeriodicWorkPolicy.KEEP, test)

    WorkManager.getInstance()!!.getStatusesByTag("test_worker")
            .observe(this, Observer { workStatus ->
                if (workStatus != null)
                {
                    for(ws in workStatus)
                    {
                        Log.d(":dump2 id ", ws.id.toString())
                        Log.d(":dump2 tag", ws.tags.toString())
                        Log.d(":dump2 state", ws.state.toString())
                    }
                }
            })

this is the result in Logcat:

 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 id: 5c6297f7-11d8-4f2f-a327-773672a7435c
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 tag: [test_worker, com.mockie.daikokuten.sync.workers.TestWorker]
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 state: ENQUEUED

Solution

  • For your periodic work request you should see

    ENQUEUED - RUNNING - ENQUEUED
    

    where the latter ENQUEUED is the state of the next work request.

    You might get very briefly a SUCCEEDED between RUNNING and ENQUEUED, but I have never seen that.

    For a onetime work request you see

    ENQUEUED - RUNNING - SUCCEEDED
    

    or whatever you return in doWork().

    (Android 8.1 API 27, 1.0.0-alpha04)