Background
I am trying to understand when I should be using bound services. It seems that I could use a repository instead in most cases.
I understand the value of a bound service to be:
- Inter process communication
- Synchronous behavior
- Lifecycle adherence (the bound service, if not started using
startService
, terminates when it has no bindings, and instantiates when it is bound to)
However, it seems those things can be accomplished with a Hilt
injected repository singleton.
My current example includes an unbound foreground service which is responsible for remote uploads of aggregated data and a UI that displays that data. Both components require authentication functionality.
Problem
To give the UI and foreground service access to authentication status and requests I could do two things:
- Inject both with an
AuthenticationRepository
. - Create an
AuthenticationService
and have both components bind to it.
Option 1 feels cleaner and more understandable. Option 2 seems to have some value that I do not understand. They both offer synchrony, communication, and lifecycle adherence.
Question
What are the pros and cons of my solutions here? How can I better define the purpose of a bound service?
CodePudding user response:
I am trying to understand when I should be using bound services
Most developers will not need one. More specifically, use a bound service when:
- the component really needs to be a service for other reasons, and
- you want synchronous communications with that service
Nowadays, most of the time, this winds up being an IPC scenario, either between a core OS process and your app or between two processes within your app. So, for example, a TileService
winds up being a bound service, because that is how Google defined the contract between the service and a core OS process.
IOW, if dependency inversion (Dagger/Hilt, Koin, etc.) will solve the problem, that probably is the better choice.
Bear in mind that wide use of DI is a relatively recent Android phenomenon (within the past 5 years), so older materials might put unwarranted emphasis on bound services.
Option 1 feels cleaner and more understandable
FWIW, I agree.