3

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

Rahul
  • 4,699
  • 5
  • 26
  • 38
  • 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 – Rahul Jul 11 '17 at 06:27
  • @M0CH1R0N: please read the above comment. If you feel this is duplicate post, I will delete it asap. Thanks. – Rahul Jul 11 '17 at 06:28
  • My bad, I reread your question. AndroidViewModel inherits 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 context as a parameter. This can be used if you want to show toasts for example. – M0CH1R0N Jul 11 '17 at 06:36
  • Could this post be reopend @IntelliJ Amiya? – M0CH1R0N Jul 11 '17 at 06:38
  • Thanks for the same. – Rahul Jul 11 '17 at 06:38
  • @M0CH1R0N Reopen – IntelliJ Amiya Jul 11 '17 at 06:41

1 Answers1

17

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.

M0CH1R0N
  • 756
  • 9
  • 19