Search code examples
androidsynchronous

How to get WorkManager Status Synchronously


I am working with WorkManager Alpha 05.

I'm developing a Service that enqueues task on demand of other applications.

It has two methods:

  1. createTask (Create a new task, given a name and a set of data, it returns and ID)
  2. checkTaskStatus (The application asks the services given a ID, the status of the task)

The communication is done via bound services using messages. That means both client and services has the correct implementations to communicate information.

Method 1 is working fine.

I have problems with method 2.

 WorkManager.getInstance().getStatusById(taskID)
            .observe(LifecycleOwner, Observer {
                status -> if (status !=null){
                    val myResult = status.state.toString()
                    statusString = myResult
                    Log.d("Task Status",myResult)
                }
            })

The observer is logging the status correctly, but I can't send back that message to the client. Is there a way to check the status in a sync way?

I don't really need to have the task attached to a LiveData.


Solution

  • Seems like SynchronousWorkManager was removed on October 11:

    Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.

    How to use ListenableFuture:

    You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.

    More info can be found here.