How to Convert a Single Activity App to MVVM Architecture
In this tutorial, we demonstrate how to convert a single activity app into the MVVM architecture, as recommended by Google. We will relate this architecture to the MVVM diagram, discussing each layer step by step. Let’s get started!
Introduction
We’re working with a classic drink suggestion app, previously used in MVC and MVP architecture tutorials. You can find those videos linked above. This app allows users to click a button to get a drink suggestion.
MVVM Architecture Overview
In the MVVM architecture:
- Activity or Fragment acts as the View.
- ViewModel manages the UI-related data.
- Repository and underlying layers make up the Model.
We will relate our architecture to the MVVM diagram step by step. You can view the MVVM diagram and its explanation in this video: MVVM | Model View View-Model Simple Real App Android.
Step 1: Create the Model
We’ll start by creating the MainRepository
class. This class will handle the main business logic of our app, such as suggesting different drinks.
public class MainRepository { /* Business logic here */ }
Move the long-executing tasks and remove Android-specific code, such as the progress bar and UI updates.
Step 2: Set Up the ViewModel
Create a new class named MainViewModel
and extend it with the ViewModel provided by Google.
public class MainViewModel extends ViewModel { /* ViewModel setup here */ }
Define LiveData variables for the progress bar and drinks:
public MutableLiveDataprogressBarVisibility = new MutableLiveData<>(); public MutableLiveData drinks = new MutableLiveData<>();
Initialize these in the constructor and create observable methods to update the UI.
Step 3: Update the MainActivity
In your MainActivity, create an instance of MainViewModel
and observe changes to update the UI components.
MainViewModel mViewModel = new ViewModelProvider(this).get(MainViewModel.class);
Observe LiveData values to update the progress bar and text view:
mViewModel.getProgress().observe(this, progress -> { /* Update progress bar */ }); mViewModel.getDrink().observe(this, drink -> { /* Update text view */ });
Handle button clicks by calling methods in the ViewModel to fetch data from the repository.
Step 4: Implement Repository Callbacks
In the repository, create a callback interface to handle drink suggestions and errors:
public interface DrinkCallback { void onDrinkSuggested(String drink); void onError(String error); }
Update the repository to use this callback and adjust the ViewModel to handle responses and update LiveData accordingly.
Conclusion
With these steps, you should have successfully converted your single activity app to use the MVVM architecture. Run the application to see the updated UI and functionality!
No comments:
Post a Comment
Share your thoughts ...