Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the difference between Android View Model and a Singleton class [closed]

Tags:

android

What exactly is the difference between Android View Model and a Singleton class if we are not using LiveData. Because a singleton class would also exist across activity orientation changes. Please let me know on this. Thanks in advance.

Thanks, Sagar

like image 366
Sagar Ekbote Avatar asked Apr 24 '18 22:04

Sagar Ekbote


People also ask

Is view model a Singleton?

No. There's no reason a ViewModel should be a Singleton. You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application.

What is the difference between AndroidViewModel and ViewModel?

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.

What is singleton class in Android?

The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just “one” instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources.

Why do we need singleton class in Java?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.


1 Answers

A singleton is unique for your entire process. A ViewModel instance is unique for a single Activity class (and, if you start multiple activities of that class, it is unique for each started activity).

like image 58
CommonsWare Avatar answered Sep 16 '22 15:09

CommonsWare