Example of a ViewModel using Google Component on Android

1

I'm trying to implement a ViewModel following that tutorial but I It seems that Google has renewed the libraries and left half the code obsolete. Someone has a functional example and its installation in the dependencies, I use Android Studio 3.0 with target version 26 .

It is not clear to me if I have to load the dependencies of lyfecircle or not Adding Components to your Project

I just need a functional example, a list of items that, when modified, can be intercepted with the observer

    
asked by Webserveis 29.11.2017 в 17:26
source

1 answer

1

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

    
answered by 30.11.2017 / 11:18
source