4

I am working on an Android application where I have to display weather data to users when they start the app. I'm following MVVM architecture and have successfully followed MVVM in all the use cases I have implemented including displaying data to users and manipulating SharedPreferences for Settings screen. I am using FusedLocationProviderClient for getting user's location, but it needs Context for instantiation. What should be the ideal way of dealing with this problem using while abiding by the MVVM architecture?

I cannot instantiate it from ViewModel since it will result in Context being passed to ViewModel hence causing potential memory leaks.

Currently, I am using FusedLocationProviderClient from my Fragment and updating data from there, but this is a very naive approach and clearly violates MVVM.

Abdul Mateen
  • 1,418
  • 1
  • 14
  • 32
  • 1
    Instantiate it in your Activity, then pass it to the ViewModel (like you should be doing with all dependencies). Look into ViewModelFactory https://proandroiddev.com/view-model-creation-in-android-android-architecture-components-kotlin-ce9f6b93a46b – Blundell Aug 29 '19 at 11:50
  • *I cannot instantiate it from ViewModel* technically you can if you use AndroidViewModel – Tim Aug 29 '19 at 11:56

1 Answers1

3

you can get Context by extending your ViewModel from AndroidViewModel and then you can do SharedPreferences related stuff there without violating MVVM pattern.

Zafer Celaloglu
  • 1,438
  • 1
  • 17
  • 28
  • 1
    *ViewModel should not contains android framework specific codes* why not? ViewModel itself is "android framework specific" – Tim Aug 29 '19 at 12:06
  • yeah right it belongs to jetpack by default so I'll change my answer accordingly – Zafer Celaloglu Aug 29 '19 at 12:09
  • I'm a little bit confused about how to fit in in MVVM. I would like to receive live updates about latitude and longitude and I think I can do it in `ViewModel` using ` `FusedLocationProviderClient` but I don't know in what method of the lifecycle it could be. Could you please help me @ZaferCelaloglu ? I'm learning Android and this is my first project. – Josseline Perdomo Oct 06 '19 at 17:27