Discuss Singletons vs. Application Context for app-global state

Technology CommunityCategory: AndroidDiscuss Singletons vs. Application Context for app-global state
VietMX Staff asked 3 years ago

According Android documentation there is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

On the other hand singletons are a nightmare for testing and, if lazily initialized, will introduce “state indeterminism” with subtle side effects. Visibility has been mentioned as another problem, and since singletons imply “global” (= random) access to shared state, subtle bugs may arise when not properly synchronized in concurrent applications.

Although the app context can be considered a singleton itself, it is framework-managed and has a well defined life-cycle, scope, and access path. Hence I believe that if you do need to manage app-global state, it should go here, nowhere else.