I have always been told that using Singleton were bad. However, every example of the Android Room implementation seems to use the Singleton approach. Can someone please explain why is this the case?
Thanks
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.
The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.
A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.
The simplest approaches are: Add an expiry timer to your singleton cache so that every so often the cache gets purged and subsquent calls fetch the updated data from source (e.g. a database) Implement a notification mechanism for the cache using something like a JMS topic/tibRV.
There are two way
1 ) you should be use dagger 2
2) make method in abstract RoomDatabase class which are provided object of class
Example:
@Database(entities = { Repo.class }, version = 1)
public abstract class RepoDatabase extends RoomDatabase {
private static final String DB_NAME = "repoDatabase.db";
private static volatile RepoDatabase instance;
static synchronized RepoDatabase getInstance(Context context) {
if (instance == null) {
instance = create(context);
}
return instance;
}
private RepoDatabase() {};
private static RepoDatabase create(final Context context) {
return Room.databaseBuilder(
context,
RepoDatabase.class,
DB_NAME).build();
}
public abstract RepoDao getRepoDao();
}
Singletons are considered evil because misusing them can make testing difficult. If the code being tested goes out and grabs a static singleton, then that singleton becomes difficult to mock for testing.
To mitigate the testing issue, your code should never get the singleton. Always receive it as a constructor parameter or have it injected by a DI framework. Of course, DI just moves the problem, because then the DI component becomes the singleton that your code reaches out and gets. But then you only have to figure out how to mock the DI component instead of a bunch of other things.
On Android, the Application
is effectively a singleton, because only one instance is created per VM. So it's a good place to host other singletons like a DI component.
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