What is the difference between ViewModel and AndroidViewModel

Rahul Sharma picture Rahul Sharma · Jul 11, 2017 · Viewed 7.8k times · Source

For anyone having this question,

As per Android Documentation,

Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. If the ViewModel needs the Application context (for example, to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor (since Application class extends Context).

Documentation can be found here : https://developer.android.com/topic/libraries/architecture/viewmodel.html

Edit: For duplicate explanation: I mean you can extend class to ViewModel as well as AndroidViewModel. When you should extend which, the above explanation is for that only. The links above tells about ViewModel of MVVM architecture in general and not the android.arch.lifecycle.ViewModel

Answer

M0CH1R0N picture M0CH1R0N · Jul 11, 2017

To expand on my comment:

The AndroidViewModel extends ViewModel, so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the Application context as a parameter.

As an example why this is useful, you could show toasts which need the Application context.