androidreferenceviewmodelandroid-architecture-componentsfusedlocationproviderclient

AAC - How to avoid reference to activity in viewmodel


The FusedLocationProviderClient that I'm using to get location information needs a reference to an activity or context. When I try to instantiate my UserLocationService - which implements FusedLocationProviderClient - inside a viewmodel, i have to pass a reference to an activity.

class UserLocationService {
public val locationUpdates: MutableLiveData<Location> = MutableLiveData()
private var fusedLocationClient: FusedLocationProviderClient
constructor(activity: Activity) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity)
...

I don't want to pass any reference to the viewmodel. What is the right approach in this case? I could use the UserLocationService directly in the fragment but my understanding is, that the viewmodel should do the instantiation und initialization.


Solution

  • You should use an AndroidViewModel.

    Edit:

    So what you can do is have the view model class.

    class MyViewModel(application: Application) : AndroidViewModel(application) {
        private val context = application.applicationContext
    
    }
    

    And then use the context for what you need.

    To initialize the view model you can do something like this in your activity.

    private val myViewModel: MyViewModel by lazy {
        ViewModelProviders.of(this).get(MyViewModel::class.java)
    }
    

    And then use it after the onCreate()