For example, I have a LocationRepository that gets the last location from the device. But I need to use the last location info in many ViewModels.

Is it better to define a private variable that holds the last location in the LocationRepository and a public getter method to reach it? After that, I can inject that Repository to every ViewModel I need.

Or should I define a lastLocation variable in a static field to be globally reachable?

Which one would be a better approach in terms of testability and single responsibility in an Android project.

1

There are 1 best solutions below

2
Akash Kashyap On

According to my understanding, making an location repository in which a variable with setter and getter would make more sense, cause you can change the logic of getting last location whenever you want from single source so this would be more maintainable And for testing also you can simply inject a fake location repository and it would be testable.

Also, You should consider about usage of last location like do you change it frequently in that case if you want to refresh it simultaneously in multiple fragments then you need to think accordingly.

I don't know the exact use-case so above is just my opinion let me know if you have any doubt.