preface

It has been said that MVVM core is bidirectional binding and projects that do not use Databinding are fake MVVMS. MVVM == bidirectional binding, MVVM == Databinding.

Today we are going to talk about MVVM in Android.

What is the MVVM

MVVM (Model-view-ViewModel) was first proposed by Microsoft. ViewModel means “Model of View” — the Model of a View.

  • Model: It only cares about the data itself, not any behavior.
  • View: responsible for receiving user input, initiating data request and displaying result page.
  • ViewModel: Takes care of the business logic and acts as a bridge between the View and the Model (a qualified ViewModel requires bi-directional binding).

The advantages of MVVM

The MVVM pattern, like the MVC pattern, mainly aims to separate the View from the Model. It has the following advantages:

  1. Low coupling. Views can be changed and modified independently of Model. A ViewModel can be bound to different “views”. The Model can remain unchanged when the View changes, and the View can remain unchanged when the Model changes.
  2. Reusability. You can put some view logic in a ViewModel and have many views reuse that view logic.
  3. Independent development. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design.
  4. Can be tested. Interfaces are harder to test, and tests can be written against the ViewModel.

The Android MVVM

In Android we implement MVVM through several components provided by Jetpack.

  • Model: corresponds to the figure aboveRepositoryLayer (network request data, local database data, etc.).
  • View: corresponds to the figure aboveActivity/Fragment
  • ViewModel: corresponding to the figure aboveViewModelLiveData.

If you look at this, you might wonder why Databinding is not used.

What two-way binding?

In short: Views change with data, and data changes with views.

The View layer Activity/Fragment updates the interface by observing LiveData in the ViewModel. The Model layer also updates notifications through LiveData in the ViewModel.

Plain text may be hard to understand, but when combined with code it becomes clear:

View layer code (TestActivity)

import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.example.fragment.project.databinding.ActivityTestBinding
import com.example.fragment.project.model.TestViewModel

class TestActivity : AppCompatActivity(a){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bind = ActivityTestBinding.inflate(LayoutInflater.from(this))
        setContentView(bind.root)

        // Use the Kotlin attribute "by viewModels ()" to delegate the ViewModel
        val viewModel: TestViewModel by viewModels()

        bind.btn.setOnClickListener {
            // Update weather information via LiveData
            viewModel.updateWeather("Cloudy")}// Update the interface by observing LiveData
        viewModel.weatherResult.observe(this) {
            bind.weather.text = it
        }

        // Get weather information from ViewModel
        viewModel.getWeather()
    }

}
Copy the code

View layer code (activity_test.xml) :

<? xml version="1.0" encoding="utf-8"? ><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <TextView
        android:id="@+id/weather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Rainy day" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/weather"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Correcting the Weather: Overcast" />
</RelativeLayout>
Copy the code

ViewModel layer (TestViewModel) :

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class TestViewModel : ViewModel(a){

    // Update data directly without writing Model

    val weatherResult = MutableLiveData<String>()

    fun getWeather() {
        // Get network data or local database data, etc
        weatherResult.postValue("Sunny day")
    }

    fun updateWeather(str: String) {
        // Update network data or local database data
        weatherResult.postValue(str)
    }

}
Copy the code

It is clear from the above code how ViewModel and LiveData work together to achieve bidirectional binding.

So far Android MVVM is all covered, originally wanted to talk about Databinding, but I feel there is no need to say more, want to learn more can go to the website. Data binding | Android developer

Thanks

That’s all for this article. If you have any questions, please point them out and we will make progress together. If you like it, please give me a thumbs-up. Your encouragement is my motivation to move forward. Thank you ~ ~

The last

Advertise your Fragmject. An entry level project, through the use of Kotlin and Jetpack family bucket system, to achieve a fully functional mainstream market standard App. Simple code, comprehensive content, detailed knowledge, quick to get started, to understand other project design ideas and packaging skills are also very helpful.