Home > Software design >  Android WorkManager: Set data into view when acitivity is active
Android WorkManager: Set data into view when acitivity is active

Time:03-20

I have an operation that runs in the background with WorkManager to get data from the phone, and send it to a remote server. However, I also need to display that data in a particular activity view whenever the user happens to go to that activity. Is there a way for me to link the Worker class with the specific Activity and perform some UI changing functions? (Change text view, etc.)

class myWorker(appContext: Context, workerParams: WorkerParameters): CoroutineWorker(appContext, workerParams) {
    private val ctx = appContext
    override suspend fun doWork(): Result {
        // Do the work here
        withContext(Main){
            //I need to be able to get data and send to server, as well as change the UI display value on a particular activity if the user happens to be on that activity.
        }

        // Indicate whether the work finished successfully with the Result
        return Result.success()

    }

CodePudding user response:

I suggest using LiveData. LiveData is an observable data class which is also lifecycle-aware. So your app components will only be updated while they are active.

The basic steps are:

  • Create a ViewModel class if you don't already have one and add a LiveData field which contains whatever data you want to persist. (See the note in the LiveData overview for reasons why this is a good idea.)
  • In your doWork function update the LiveData object as necessary. You might want to create functions in your ViewModel to perform operations on the data.
  • In your activity call observe on the LiveData object and update the UI as necessary.
  • Related