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()
}
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:
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.)doWork
function update the LiveData object as necessary. You might want to create functions in your ViewModel to perform operations on the data.observe
on the LiveData object and update the UI as necessary.