Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ViewModel and AndroidViewModel [duplicate]

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

like image 642
Rahul Sharma Avatar asked Sep 16 '26 06:09

Rahul Sharma


1 Answers

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.

like image 150
M0CH1R0N Avatar answered Sep 18 '26 19:09

M0CH1R0N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!