0

So, I am using workmanager to retrieve data from an FTP server. I have to display one type or information or another type deppending on the state of the worker.

I was using getWorkInfoByIdLiveData on the viewmodel and I was observing the state of the worker on the activity. But, as the Observer is almost deprecated I am trying to use Flow instead.

The problem that I have is that I don't know why, I can't use the asStateFlow() on the livedata. enter image description here

Does anyone know a way to observe the state of a worker without using LiveData and Observer?

Thank youuu

General Grievance
  • 4,555
  • 31
  • 31
  • 45
BalknGrl6
  • 3
  • 2
  • I don't find any `Flow` info in the `WorkManager` documentation. – Sam Chen Jul 13 '22 at 16:23
  • I don't think that's the way you transform a LiveData to StateFlow. May this can help you: https://chao2zhang.medium.com/converting-livedata-to-flow-lessons-learned-9362a00611c8 – writer_chris Jul 15 '22 at 18:28
  • From the docs, it looks very much like `LiveData` is what you should be using to observe `WorkManager` state. I can't see anything saying that `LiveData.observe` is being deprecated any time soon. Where are you seeing information saying that it will be deprecated? – Sam Jul 18 '22 at 13:33
  • @Sam https://developer.android.com/reference/java/util/Observer here. Anyway I was able to find a solution. I used the ".asFlow" extension to convert the livedata to a Flow. Now everything work fine, even in API 33 :) – BalknGrl6 Jul 19 '22 at 07:27
  • @writer_chris Thank you very much. I was having the problem that I didn't have my dependencies updated, so the extension ".asFlow" wasn't appearing. But now everything is working as expected. Thank you for your time :) – BalknGrl6 Jul 19 '22 at 07:29

1 Answers1

0

Add the LiveData-ktx dependency to your build.gradle:

androidx.lifecycle:lifecycle-livedata-ktx:2.6.1

Then you can convert LiveData to Kotlin Coroutine's Flow.

val operation = WorkManager.getInstance(context).enqueue(myRequest)
operation.state.asFlow()
M.Ed
  • 969
  • 10
  • 12