0

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.

berchoes
  • 19
  • 3

1 Answers1

1

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.

  • Location thing was only an example. The use-case is actually caching a value that is fetched from a data source and is not necessarily to be fetched again every time it will be used. For example it will be used by multiple viewmodels. The question is where to keep that cached variables. – berchoes Apr 12 '23 at 09:12
  • I still suggest to use repository, If you're using any dependency injection then in that case you can provide this repository to every viewmodel and you can make variable in repository that will cache the location. Now you don't need to refresh variable it will be available in repository and you can provide a single instance. – Akash Kashyap Apr 12 '23 at 10:04