oznecro
oznecro

Reputation: 457

Should repository classes implement the singleton pattern?

In this sample app: https://github.com/googlesamples/android-sunflower

The repository classes (PlantRepository.kt, GardenPlantingRepository.kt) are singletons and so is the injector utility object (InjectorUtils.kt).

Why are the repository classes singletons when the injector utility object is already one?

Upvotes: 9

Views: 8027

Answers (2)

Sam
Sam

Reputation: 140

Yes, in most cases, repository classes should be Singletons. This is especially useful when using a dependency injection framework like Dagger, where you can provide repositories as singleton classes in a network module.

Why? Because you usually want a repository class to be created once and used throughout the application's lifetime. For example, in an online store app that sells cakes and pastries, you may have a repository that contains methods related to customer details such as shipping and billing addresses. This repository will be used throughout multiple user journeys in the app, and recreating the instance every time would be inefficient.

Moreover, if two screens use the same repository, it's preferable to use the same instance of the repository for both screens instead of creating separate instances for each of them. This also ensures consistency in the behavior of the repository across the app, because quite often your repositories in huge apps contain some other logic that given two instances of the same repository may violate the Single Source of Truth principle.

Also, it's just easier to think of repositories as Singleton classes, because it eliminates the overhead of thinking what scope you should assign to the class.

A rule of thumb that I follow is that most of the classes in the data layer that need to be provided by Dagger should be singletons, while most of the classes in the UI layer that should be provided by Dagger should have their own scope.

Upvotes: 1

Alessio
Alessio

Reputation: 3193

InjectorUtils is a singleton, because they want to use it as an helper class from anywhere in the code in a static way, and through it been able to get a PlantRepository, a GardenPlantingRepository, and some factories. Now, if you think about Repositories, they are classes to provide fast access to in-memory datasets (which can be then updated asynchronously), so there wouldn't be any reason to create any time a new instance of a repository (that means any time new memory will be allocated), given its methods are only wrappers around the dao's methods; in fact, if you notice, the dao is passed to such singleton repositories in getInstance(), therefore allowing the binding between the wrapper methods and the dao. So, they are singletons to avoid allocating new memory, passing instead around the same allocated memory (because it contains only wrappers)

Upvotes: 4

Related Questions