I currently have an app with a ForegroundService for all server/API interactions, and a Room database for local persistence. I have been trying to implement an AndroidViewModel to help with data persistence and quick UI refreshes.
However, as per the documentation, ViewModels can't be implemented in Services, and so far I've used the Service to update information locally and notify components using LocalBroadcasts (which is what I want to eliminate using ViewModels and Observers).
I need to have the service running as the app needs to keep running in the background (its a mission critical app and the app getting closed means that the user will not be available to provide critical services), and update certain information on a periodic basis (nearby requests, etc. ).
So to ask the core question -
- How do I separate the service from the ViewModel, and if the service has the latest synced data from the servers, how do I update the (Mutable)LiveData lists in my ViewModel?
- This article and this answer to a question here on SO says it is better to separate the ViewModel from the Repository while this other one gives an example of including the Room database inside the ViewModel. Which is the better option?
Some of my ViewModel code is as follows:
public class HouseCallViewModel extends AndroidViewModel {
private String TAG = HouseCallViewModel.class.getSimpleName();
private MutableLiveData<List<HouseCall>> housecallList;
private MutableLiveData<List<HouseCall>> openHousecalls, confirmedHousecalls, closedHousecalls, missedHousecalls, userCancelledHousecalls, respCancelledHousecalls;
private MutableLiveData<List<Incident>> incidentList, openIncidents;
private MutableLiveData<List<Incident>> closedIncidents, usercancelIncidents, respcancelIncidents;
RevivDatabase database;
Context context;
public HouseCallViewModel(Application application) {
super(application);
// DANGER WILL ROBINSON
context = application.getApplicationContext();
database = Room.databaseBuilder(this.getApplication(),
RevivDatabase.class, application.getResources().getString(R.string.database)).build();
}
public LiveData<List<HouseCall>> getHousecallList() {
if (housecallList == null) {
housecallList = new MutableLiveData<>();
loadHousecalls(); // need to call API and sync
}
return housecallList;
}
public LiveData<List<HouseCall>> getIncidentList() {
if (incidentList == null) {
incidentList = new MutableLiveData<>();
loadIncidents(); // need to call API and sync
}
return housecallList;
}
// other constructors, getters and setters here, and functions to update the data
}
> my Activity uses the ViewModel to access live data. Thanks so much for the insightful answer though. If you could edit your answer and add this as a solution, I would be happy to accept it :)
– kilokahn Jul 27 '18 at 20:22