I am using WorkManager in my app to upload big videos to server. First I make chunks of video file and then upload through work manager. I need to show the progress of upload on UI, and Work manager is launched from my viewmodel. I am using single activity with jetpack compose, and my viewmodel is scoped to activity. When app is alive everything works fine, but if its instance is cleared from memory while upload is in progress, upload continues to happen but when app relaunches, since the viewmodel instance is new, I am unable to get status of upload from work manager and update UI. Any idea how to tackle this? Any help much appreciated. This is how I launch my WorkManager. Currently creating WM for each chunk due to some progress update issues in single WM per video.
private fun uploadVideo(chunk: VideoData) {
if (!appContext.isOnline(analyticsManager)) {
showNoNetwork.value = true
}
val workManager: WorkManager = WorkManager.getInstance(appContext)
val uploadWorkRequest: WorkRequest = OneTimeWorkRequestBuilder<UploadVideoWorkManager>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setInputData(
workDataOf(
ParamKeys.VIDEO to videoData.value?.toJsonString()
)
)
.build()
workManager.enqueue(uploadWorkRequest)
val liveData = workManager.getWorkInfoByIdLiveData(uploadWorkRequest.id)
workInfoObserver = androidx.lifecycle.Observer { workInfo ->
updateUploadStatus(workInfo, liveData)
}
liveData.observeForever(workInfoObserver!!)
}
Is using broadcast receiver the only solution? or is there any other ways?
Check this article
You can send data from work manager this way:
fun doWork(): Result {
var progress = 0
setProgress(
workDataOf("KEY" to progress)
)
// other code
}
And collect it with kotlin Flow:
val workProgressFlow: Flow<Int> = WorkManager.getInstance(context)
.getWorkInfosLiveData(WorkQuery.fromUniqueWorkNames("work_name"))
.asFlow()
.map { it.single().outputData.getInt("KEY", 0) }
If your work is unique it must persists data after app relaunch.
If there's something I don't understand, write down the problem in detail