1

Storing state inside the Application class or a singleton has the added benefit of sharing across activities too (is there a simple way to share one ViewModel across two activities I'm unaware of?)

Also a singleton can be as android free as a ViewModel can be, so testing locally (without an android device or emulator) shouldn't be an issue.

kptlronyttcna
  • 1,257
  • 1
  • 12
  • 20

1 Answers1

1

Storing state inside the Application class or a singleton has the added benefit of sharing across activities too

It is also a memory leak. Use that for things that are truly process-wide, and make sure that you are taking steps to cap the memory use (e.g., limit the size of any caches that you use).

What's the benefit of storing state in ViewModel (from Android Architecture Components) rather the Application class or a Singleton?

A ViewModel, retained fragments, and onRetainCustomNonConfigurationInstance() are for holding state unique to a running activity, across configuration changes for that activity. At most — if you screw something up — they temporarily cause a memory leak, but that will get cleared up as soon as the overall activity is destroyed. Also, because these are scoped to an individual activity, you can easily have N of them for N logical activity instances, which may or may not be practical with process-wide solutions.

In general, in computer programming, we aim to keep our data in the narrowest scope possible ("information hiding"). Using things that are global in scope runs counter to that design principle. Hence, using singletons is possible, but should be reserved for cases where it is unavoidable or vastly superior to using a narrower scope. In Android, we use singletons far more than you would in ordinary Java development, where singletons are often considered to be evil.

CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253