简体   繁体   中英

Update Fragment UI from background service

I have some work that must execute even in cases when user closes the app and removes it from used apps (kills it completely). The flow goes like this: User selects an item from list after which new screen is opened, then the user is able to select an option which is calling rest api and performing work (in background service), computing and caching data locally (it can take up to 30-45 seconds), this background service must update Fragment UI. If for example user closes the app, and opens the same screen again (and the work is still in progress) I should update the Fragment UI accordingly with the current state of execution. What is the best way to handle this?

You should be using CoroutineWorker for long-running background tasks.

You can then observe the workers progress either the official way , or you can have our own observable in the worker's companion object, ie:

 class ProgressWorker(context: Context, parameters: WorkerParameters) :
    CoroutineWorker(context, parameters) {

    companion object {
        private const val delayDuration = 1L

        val progressObservable = MutableStateFlow(0)
    }

    override suspend fun doWork(): Result {
        updateProgress(0)
        delay(delayDuration)
        updateProgress(100)
        return Result.success()
    }

    private suspend fun updateProgress(progress: Int) {
        progressObservable.emit(progress)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM