For the installation of the Google components it is only necessary to add the app.gradle
directive
implementation "android.arch.lifecycle:extensions:1.0.0"
To create a ViewModel (Presenter) extend the class ViewModel
The data that wants to be observed define them with MutableLiveData
if it is a list
private MutableLiveData<List<String>> fruitList;
Create the function to retrieve the data list
LiveData<List<String>> getFruitList() {
if (fruitList == null) {
fruitList = new MutableLiveData<>();
loadFruits();
}
return fruitList;
}
For the filling task use background tasks, this avoids freezing the UI
private void loadFruits() {
// do async operation to fetch users
Handler myHandler = new Handler();
myHandler.postDelayed(() -> {
List<String> fruitsStringList = new ArrayList<>();
fruitsStringList.add("Mango");
fruitsStringList.add("Apple");
fruitsStringList.add("Orange");
fruitsStringList.add("Banana");
fruitsStringList.add("Grapes");
long seed = System.nanoTime();
Collections.shuffle(fruitsStringList, new Random(seed));
fruitList.setValue(fruitsStringList);
}, 5000);
}
To detect that the activity where the observer has been completely closed, the event onCleared
is used
@Override
protected void onCleared() {
super.onCleared();
Log.d(TAG, "on cleared called");
}
In the activity to get the changes in the list and modify the UI to show the changes
ViewModelProviders.of(this).get(youViewModel.class);
model.getFruitList().observe(this, fruitlist -> {
// update UI from List List<String> fruitlist
});
}
Extracted from that tutorial in English