Update Fragment UI from background service

Solution 1:

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, i.e.:

 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)
    }
}