Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndroidViewModel vs ViewModel

AndroidViewModel provides Application context

If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call getApplication(), otherwise use the regular ViewModel (VM).

AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! However, having static Application instance is not as bad as you might think because there is only one Application instance in the running application.

Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.

See Also about Application Instance

AndroidViewModel Problematic for unit tests

AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.


Finally I got something a simpler explanation, a bit...... ...The AndroidViewModel class is a subclass of ViewModel and similar to them, they are designed to store and manage UI-related data are responsible to prepare & provide data for UI and automatically allow data to survive configuration change.

The only difference with AndroidViewModel is it comes with the application context, which is helpful if you require context to get a system service or have a similar requirement. the bold text makes it clearer to sense it.


AndroidViewModel is subclass of ViewModel. The Difference between them is we can pass Application Context which can be used whenever Application Context is required for example to instantiate Database in Repository.

AndroidViewModel is a Application context aware ViewModel.

AndroidViewModel:

public class PriceViewModel extends AndroidViewModel {
private PriceRepository priceRepository;

public PriceViewModel(@NonNull Application application) {
    super(application);
    priceRepository= new PriceRepository(application);
    allPrices = priceRepository.getAllPrices();
}

ViewModel:

public class PriceViewModel extends ViewModel {
public PriceViewModel() {
    super();
}

You Should use AndroidViewModel only when you require Application Context.

You should never store a reference of activity or a view that references a activity in the ViewModel.Because ViewModel is designed to outlive a activity and it will cause Memory Leak.