I upload the file with workmanager. I want to obse...
# compose
h
I upload the file with workmanager. I want to observe the workmanager progress and show file upload progress in ui. I also update the progress variable with the high order function. The problem is my screen is constantly recomposed. I see that the progress suddenly reaches 100. In the following example in WorkManager codelab, it is done with viewbinding(https://developer.android.com/codelabs/android-adv-workmanager#4) How can I update progress bar on ui according to the progress of worker in workmanager ?
Copy code
private fun progressObserver(state: (Float) -> Unit): androidx.lifecycle.Observer<List<WorkInfo>> {
    return androidx.lifecycle.Observer { listOfWorkInfo ->
        if (listOfWorkInfo.isNullOrEmpty()) {
            return@Observer
        }

        listOfWorkInfo.forEach { workInfo ->
            if (WorkInfo.State.RUNNING == workInfo.state) {
                val progress = workInfo.progress.getInt(PROGRESS, 0)
                state(progress.toFloat())
            }
        }
    }
}
Copy code
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun EditProfileComposableComponent(
    modifier: Modifier,
) {
    var progress = remember { mutableStateOf(0.1f) }
    profileViewModel.progressWorkInfoItems.observe(lifecycleOwner, progressObserver(
        state = { state -> progress.value = state }
    ))  
     LinearProgressIndicator(
            progress = progress.value,
            modifier = modifier.fillMaxWidth(1f),
            backgroundColor = backgroundColor
      )
   ...
}
h
I think what you are looking for is
observeAsState
☝️ 3
t
For me it looks ok. But you need to respect the lifecycle of compose components. You should use DisposableEffect() to subscribe unsubscribe for state updates.
i
observeAsState()
does all that for you. Just use that
👍 1
h
Thank you for the answers. i changed the code like this.
Copy code
val progressWorkInfo = profileViewModel.progressWorkInfoItems.observeAsState()
but I don't understand the thing how do I access the worker's progress values to give it to LinearProgressIndicator? @Ian Lake
i
The codelab you're following published an int as progress and uses
workInfo.progress.getInt(PROGRESS, 0)
👍 1