Android Design Pattern - MVVM (Part 2)

  • Ivan Žarković

Hello reader,

this is the second part of How to Build Weather Application using the Android Design Pattern (MVVM). In the first part, we have covered how to implement a Model View ViewModel pattern in the Android application.
Besides Activity or Fragment which is created automatically, we built a ViewModel that holds our business logic service which we used to fetch data from RESTful API and we updated UI (MainActivity) from our ViewModel class. The reason we did this is to save the current state of an application.
For example, our user can open the app and lock the phone for a few hours, when the user unlocks the phone again, everything will be in the same place as it was before locking.
One more example is when a device changes its state eg. screen rotation. That means that previous activity is being destroyed and recreated into a new layout. To achieve this we kept our data inside a ViewModel class and pass it to newly created Activity so that whenever user activity is being recreated, data presented on the screen remains the same.

Creating a Repository as a part of MVVM Design Pattern

In the first part of the guide, we made only ViewModel which is handling the connection to a web service and business logic. We want to separate those two things by adding the repository. It will be used for fetching the data from the API service.
So go to the com.example.weatherapp and create new package "repository" and inside create a java class called WeatherRepository:

private static WeatherRepository instance;
    MutableLiveData<Model> data = new MutableLiveData<>();

    //create cunstructor using Singleton pattern
    public static WeatherRepository getInstance(){
        if(instance==null){
            instance = new WeatherRepository();
        }
        return instance;
    }

    public MutableLiveData<Model> getWeatherData(){
        loadWeatherData();
        return data;
    }

 

After this, we can migrate our loadWeatherData() method to our newly created repository, after which we need to adjust ViewModel:

private MutableLiveData<Model> weatherData;
    private WeatherRepository mRepo;

    public void init(){
        if(weatherData!=null){
            return;
        }
//create repository instance
        mRepo = WeatherRepository.getInstance();
//now we will load it asynchronously from the server in this method via WeatherRepository
        weatherData = mRepo.getWeatherData();
    }

    public LiveData<Model> getWeather() {
//if the data is null
        if (weatherData == null) {
            weatherData = new MutableLiveData<Model>();
            init();
        }
//finally we will return the data
        return weatherData;
    }

 An approach like this gives us more space to change, adjust and eventually expand the project.

 

Thank you for reading,

see you soon with the third note on How to transfer Adobe XD design to the Android application.

Article Subscription