I have a project, in which I have successfully implemented location tracking feature, and is working perfectly. I am tracking users current location using fused location provider in every 30 seconds.(tracking starts when MainActivity started).
Now I am planning to update that project with newly introduced android architecture components. But I don't know how to implement location tracking with view model.Where is the right place to start location tracking, in MainActivity or Application class? Should I use ViewModel or AndroidViewModel? How to achieve this.
The correct way would be to have a TrackingRepository
where you do all calculations in a background thread of the device location. Create a MutableLiveData
where you will assign the location. Then update its value using postValue()
or setValue()
. Write a public getter for this MutableLiveData
. This repository will be your location API.
Then your ViewModel
should call the method of your repository and assign its result to a LiveData
variable of the ViewModel
. Then in your Fragment/Activity observe the liveData of your ViewModel
. Just as the Guide to App Architecture does.
Remember to use dependency injection which really helps with the new architecture.