Dagger 2 on Android. Different ways to store and access a @Singleton Component

前端 未结 2 1117
孤街浪徒
孤街浪徒 2021-02-19 11:15

This is the Nth question about how to store @Singleton scoped Dagger 2 Components whose lifetime should equal the application\'s lifetime.

In Android apps using Dagger 2

相关标签:
2条回答
  • 2021-02-19 11:53

    With 1 and 2 you are using static references. This is a good thread about why to avoid them

    Why are static variables considered evil?

    So the only option left is the 3rd. That is what I am using on my projects. About if you should pass the context as argument or not, depends on the architecture of your project and how you designed the Dagger dependencies. Personally I don't have that problem because I am only injecting in Activities/Fragments. Can you give me an example where you need to pass the context to inject dependencies?

    0 讨论(0)
  • 2021-02-19 12:01

    I use method #2. The main problem with method #1 is that you're exposing a mutable field. If your module doesn't require a Context to construct, you could make the field final. But as a matter of style, I still prefer not to expose fields.

    You should normally avoid global state, especially in Android because of the complex and sometimes unintuitive lifecycles of components and the VM itself. But Application is the exception to this rule. Exactly one instance of it exists per VM, and its onCreate() method is called exactly once, before any other component is created. This makes it an acceptable place to create and store a static singleton.

    0 讨论(0)
提交回复
热议问题