Die gesamte Arbeit ist in eine Reihe verketteter Worker aufgeteilt, und ich habe Probleme, dem Benutzer den Fortschritt der Worker anzuzeigen (anhand der Fortschrittsleiste). .
Ich habe versucht, ein Tag zu erstellen und es den verschiedenen Workern hinzuzufügen und innerhalb der Worker den Fortschritt anhand dieses Tags zu aktualisieren, aber beim Debuggen erhalte ich immer den Fortschritt „0“.< /p>
Eine andere Sache, die mir aufgefallen ist, ist, dass die Die Liste der Arbeitsinformationen von workManager wird jedes Mal größer, wenn ich mit der Arbeit beginne (auch wenn die Arbeiter ihre Arbeit beendet haben).
Hier ist mein Code:
Code: Select all
//inside view model
private val workManager = WorkManager.getInstance(appContext)
internal val progressWorkInfoItems: LiveData
init
{
progressWorkInfoItems = workManager.getWorkInfosByTagLiveData(TAG_SAVING_PROGRESS)
}
companion object
{
const val TAG_SAVING_PROGRESS = "saving_progress_tag"
}
//inside a method
var workContinuation = workManager.beginWith(OneTimeWorkRequest.from(firstWorker::class.java))
val secondWorkRequest = OneTimeWorkRequestBuilder()
secondWorkRequest.addTag(TAG_SAVING_PROGRESS)
secondWorkRequest.setInputData(createData())
workContinuation = workContinuation.then(secondWorkRequest.build())
val thirdWorkRequest = OneTimeWorkRequestBuilder()
thirdWorkRequest.addTag(TAG_SAVING_PROGRESS)
thirdWorkRequest.setInputData(createData())
workContinuation = workContinuation.then(thirdWorkRequest.build())
workContinuation.enqueue()
//inside the Activity
viewModel.progressWorkInfoItems.observe(this, observeProgress())
private fun observeProgress(): Observer
{
return Observer { listOfWorkInfo ->
if (listOfWorkInfo.isNullOrEmpty()) { return@Observer }
listOfWorkInfo.forEach { workInfo ->
if (WorkInfo.State.RUNNING == workInfo.state)
{
val progress = workInfo.progress.getFloat(TAG_SAVING_PROGRESS, 0f)
progress_bar?.progress = progress
}
}
}
}
//inside the worker
override suspend fun doWork(): Result = withContext(Dispatchers.IO)
{
setProgress(workDataOf(TAG_SAVING_PROGRESS to 10f))
...
...
Result.success()
}