Ahsan Saeed
Ahsan Saeed

Reputation: 741

EditWorkManager method getWorkInfoByIdLiveData not giving the WorkInfo

I'm trying to get my WorkerInfo with the getWorkInfoByLiveData method that exists in the WorkManager instance.

val workInfo = workManager.getWorkInfoByIdLiveData(uuid).value

The WorkInfo is always null. Also, I'm calling this method from the main thread.

The scenario of how I'm checking this method. I try to enqueue my worker when a user sends a network request and if the internet is not connected I simply register a work with the WorkManager. After some time if I try to get the WorkerInfo with the UUID, it'll always give me null.

Note: When calling getWorkInfoByLiveData the Worker is not executed at that time.

Don't I'm expecting from WorkManager to give me WorkInfo with ENQUEUED State.

Edit 1: So, another scenario would be like this, the app on which I'm working is like a social app. Now after registering a first worker, let's say the user don't want to see the posts from a specific user so this where I need to register my second worker because the user internet is not available at this time. Now what I need to do is to cancel the previously registered worker and then create a Chain of workers with not to show post of a user to beginWith and then the fetch all posts. Now in order to cancel the worker, I check that if the previous worker is still in Enqueued State then cancel it and create a new chain or workers.

Here is the code.

fun Context.isWorkerRegistered(uuid: UUID?): Boolean {
   val id = uuid ?: return false
   val workerInfo = workManager.getWorkInfoByIdLiveData(id).value
   return workerInfo?.state == WorkInfo.State.ENQUEUED
}

The workInfo instance is always null.

Upvotes: 4

Views: 1342

Answers (1)

pfmaggi
pfmaggi

Reputation: 6476

Note: Livedata won't calculate the value until an active observer is added.

getWorkInfoByIdLiveData() returns a LiveData<WorkInfo> that you need to observe to get the workInfo value:

val status = workManager.getWorkInfoByIdLiveData(uuid)
                        .observe(this, Observer{ workInfo ->

    if (workInfo!=null){
        // ...
    }
}

you can take a look at the WorkManager's codelab to see how it can be used.

Upvotes: 2

Related Questions