Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2 multiprocess dependencies

I have an ApplicationComponent which provides access to my repositories : LocationRepository, PlaylistRepository, ...

These repositories are all @Singleton. So far so good.

My issue is that I need to access to one of these repositories (LocationRepository) from a Service in another process.

I could just do new LocationRepository(params) in that service (and I do need another instance since the service lifecycle is independent from the app's one) but that's not very safe.
If I change how the service is created in dagger, I could forget to update the service as well.

So is there a way to have a part of a component (here the LocationService) declared separately and instantiated the same way in two different component ?

like image 728
Teovald Avatar asked Sep 29 '26 11:09

Teovald


1 Answers

If I understand correctly, you wish to ensure that the definition (and instantiation logic) of your LocationRepository is identical across two processes.

If that's the case, you could always pull it in to its own library module, and have both processes take that module as a dependency. You could even put a @Component interface there, too.

I wouldn't recommend it.

You would end up with two instances of the same singleton. This is unavoidable because processes are isolated from each other, and do not share memory. Each has its own VM. This would result in hard-to-debug data races, as both processes read from and write to a single resource.

It makes more sense to me that one process would "own" it, and the other process would access it via inter-process communication, e.g. via an AIDL interface, like the Google Play Services clients.

I imagine that one process hosts a long-lived Service, and the other hosts your UI. In this case, your Service is a natural owner of the singleton, and your UI process would use an implementation of the repository that communicates with the service. This could even participate in injection; make a module that @Provides a LocationRepository, and give it a bound service connection.

This is all really high-level; I hope it makes sense and is helpful. Happy to provide more detail if I can!

like image 192
Ben Avatar answered Oct 02 '26 02:10

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!