Search code examples
dagger-2android-viewmodel

Why using AndroidViewModel?


I read a lot of ViewModel derived from AndroidViewModel, which then requires of course an application reference.

class SomeViewModel(application: Application) : AndroidViewModel(application) 
  1. But why would one do this? It hurts me to see application handed over to ViewModel. What would be an acceptable use case for this?
  2. If there is any reason to use AndroidViewModel, can one not derive from ViewModel + use dagger2 for the application inject?

Solution

  • Not all codebases are created equal. AndroidViewModel can be a useful tool for incremental refactoring in "legacy" codebases that don't have many abstractions or layering in place (read: Activity/Fragment god objects).

    As a bridge from a "legacy" codebase, it makes sense to use it in this situation.

    1. But why would one do this? It hurts me to see application handed over to ViewModel. What would be an acceptable use case for this?

    The use case for AndroidViewModel is for accessing the Application. In a "legacy" codebase, it's relatively safe to move "Context/Application-dependent code" out of Activities and Fragments without requiring a risky refactor. Accessing Application in the view model will be necessary in that scenario.

    1. If there is any reason to use AndroidViewModel, can one not derive from ViewModel + use dagger2 for the application inject?

    If you're not injecting anything else, then at best it's a convenient way to get an Application reference without having to type cast or use any DI at all.

    If you're injecting other members, be it with a DI framework or ViewModelFactory, it's a matter of preference.

    If you're injecting a ViewModel directly into your Activity/Fragment, you're losing the benefits the platform is providing you with. You'll have to manually scope the lifecycle of your VM and manually clear your VM for your UI's lifecycle unless you also mess around with ViewModelStores or whatever other components are involved in retention. At that point, it's a view model by name only.