Jetpack's ViewModel and LiveData

The renderings to be achieved in this chapter

Insert picture description here

Advantages of ViewModel

1. Page configuration changes and data are not lost.
When the device is rebuilt due to configuration changes (horizontal and vertical screen rotation, soft keyboard mode, device resolution, permission switch), the activity/fragment is rebuilt, and the data in the ViewModel will not be lost as a result (data save and read Let's talk about below), with LiveData, you can immediately receive the latest saved data after the page is rebuilt to re-render the page.

2. Life cycle sensing
It is inevitable that some network requests or data processing will be done in the ViewModel. You can override the onCleared() method to terminate some cleanup operations and release memory. This method is called when the host is onDestroy.

3. Data sharing
For single Activity, multiple Fragment pages, ViewModel can be used to realize data sharing between pages

Import ViewModel in jetpack

   def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

ViewModel case

1. First, we create our own myViewModel to inherit ViewModel

Here is used to store the variable numer

import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    
    
    public int number =0;

}

2. To instantiate the myviewmodle object,
we need to note that we need to manually import the ViewModelProviders dependency
Insert picture description here

 //创建MyViewModel
        myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

3. Operate the value in myviewmodel by clicking the button


public class MainActivity extends AppCompatActivity {
    
    
MyViewModel myViewModel;
TextView textView;
Button button1,button2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init_view();

        //创建MyViewModel
        myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        textView.setText(String.valueOf(myViewModel.number));
        button1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                myViewModel.number++;
                textView.setText(String.valueOf(myViewModel.number));
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                myViewModel.number+=2;
                textView.setText(String.valueOf(myViewModel.number));
            }
        });
    }

    private void init_view() {
    
    
        textView=findViewById(R.id.textView);
        button1=findViewById(R.id.add);
        button2=findViewById(R.id.button2);
    }
}

Insert picture description here

This example uses ViewModel, which will not cause data loss when the screen is upside down.

Overview of LiveData

The official explanation
LiveData is a class that can be observed and holds data. Unlike other regular observables, it cares about the life cycle of the component, which means that it respects the life cycle of Activity, Fragment and Service, which can ensure that only Update observers in components in Start and Resume (life activity cycles).

Advantages of using LiveData:

1. Ensure that the ui is synchronized with the data. LiveData follows the observer pattern. LiveData will notify you when the component life cycle changes. You can merge code to update the UI in these observer objects. Because of the life cycle management, you can update the UI in the observer with confidence .
2. No memory leaks. Because the observer is bound to LifeCycle, with the destruction of LifeCycle, the observer will be automatically cleaned up.
3. Stopping activities will not cause a crash. If the life cycle of the component where the observer is located is not active, such as the activity in the stack, the observer will not receive data at this time.
4. No need to manually manage the life cycle. The ui component only observes relevant data, and does not need to end or start observation. LiveData will automatically manage these, because it knows the life cycle changes while observing.
5. Always the latest data. When an activity returns from the background, it will immediately receive the latest data.
6. Appropriate configuration changes. If the activity or fragment is rebuilt due to configuration changes, such as screen rotation, it will immediately receive the latest data.
7. Share resources. You can inherit a LiveData object and use the singleton pattern to package it into a system service so that it can be shared in the app. This LiveData object is once connected to the system service, and all observers who need the resource can observe the object.

Why use LiveData

Earlier we saw that when only using ViewModel, we have to call textView.setText(String.valueOf(myViewModel.number));to re-assign every time the data changes . Is there any way to save this step? Then LiveData comes in handy

1. First of all, we still create the ViewModel. It is worth noting that the type of our data has changed. Now we use MutableLiveData<Integer> Numberit and assign the number in the constructor.

LiveData case


public class LiveData extends ViewModel {
    
    
     private  MutableLiveData<Integer> Number;

    public MutableLiveData<Integer> getNumber() {
    
    
        if(Number == null){
    
    
            Number = new MutableLiveData<>();
            Number.setValue(0);
        }
        return Number;
    }
    //该函数用于对数据进行操作,比如+1,或者-1
    public  void addNumber(int n){
    
    
        Number.setValue(Number.getValue()+n);
    }
}

2. Use the observer mode to monitor data changes,liveData.getNumber().observe(this, new Observer<Integer>() {


public class LiveDataActivity extends AppCompatActivity {
    
    
ImageView button1,button2;
TextView textView;
LiveData liveData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_data);
        init_view();
        //获取ViewModel对象
        liveData = ViewModelProviders.of(this).get(LiveData.class);
        //添加观察者,监听数据的改变,并在数据改变的时候重新赋值
        liveData.getNumber().observe(this, new Observer<Integer>() {
    
    
            @Override
            //当数据改变就呼救此函数
            public void onChanged(Integer integer) {
    
    
                //显示当前的数
                textView.setText(String.valueOf(integer));
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                //加1操作
                liveData.addNumber(1);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                //减1操作
                liveData.addNumber(-1);
            }
        });

    }
    private void init_view() {
    
    
        textView=findViewById(R.id.textView2);
        button1=findViewById(R.id.imageView);
        button2=findViewById(R.id.imageView2);

    }
}

Guess you like

Origin blog.csdn.net/qq_45353823/article/details/107851896