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
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With