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

前端 未结 2 1081
孤街浪徒
孤街浪徒 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 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.

提交回复
热议问题