Let's say a service 'MyService' is already running, doing some work like copying a file in background, before an activity, 'MyActivity' is launched. Then user launches the activity. How can I retrieve what file is being copied in MyService when MyActivity starts so that I can show it in UI?

I haven't attached a code because I want a generic answer to this. The task could be anything, like downloading a file. I'm learning coding and experimenting with services. So, I'm just copying a bunch of big files in a service.

If needed, I'll post the code.

1 Answers

0
Francesc On

A possible solution to this is to have the service expose a RxJava bus (or similar) where it pushes updates on what it is doing. Then the Activity will subscribe to this bus in onResume and unsubscribe in onPause and will display info based on what is being pushed on the bus.

You could have a single bus, where the event itself carries data (like the percentage of copy), or you could have multiple buses, for instance one for state (idle, copying, ...) and another one for details on the state (like a bus for percentage of copy done).

A possible implementation for the states would be

sealed class State {
    object Idle : State()
    class Copying(val percent: Float): State()
}

then in your Service you would have

val stateBus = BehaviorSubject.create<State>()

then

stateBus.onNext(Copying(.5f))