Android Jetpack(二)LiveData

        LiveData  2017 Google I / O the General Assembly and with the launch of the LifeCycle. They are components Components of Architecture. LiveData is a data type holds observable . Conventional can be observed in different classes, LiveData has a life cycle-aware , meaning that it follows the other application components (Activity, Fragment or Service) life cycle. This awareness can only ensure LiveData update application components are active observer lifecycle state.

        Typically, LiveData not used alone, but used in conjunction with other components of Jetpack. In my previous blog Android Jetpack (a) ViewModel  , we learned, use ViewModel can store and manage logical UI data independent. But each time the data changes, is still driven by references (References) Data refresh the page.

        

        The benefits of using LiveData of: adding the data corresponding to the observation requires the observer  the Observer, when the data changes, data may be automatically refreshed at the interface. That is no longer necessary references (References) to refresh the page.

        

 

(A) LiveData advantage

        Use LiveData has the following advantages:

  • Ensure compliance with data interface status

        LiveData follow the observer mode. When the lifecycle status changes, LiveData will notify Observer objects. You can integrate the code to update the Observer interface in these objects. The viewer can be updated each time a change occurs in the interface, rather than updating the application interface each time the data changes.

  • Memory leak does not occur

        LifeCycle observer will bind to the target, and self-cleaning after it was associated with the life cycle of destruction.

  • Activity will not stop and crash

        If the observer's life cycle in a non-active state (such as return stack Activity), then it will not receive any LiveData event.

  • Eliminates need for manual processing lifecycle

        Interface components simply observe the relevant data, will not stop or resume observation. LiveData will automatically manage all these operations, because it is related lifecycle state changes can be perceived in the observation.

  • Data is always up to date

        If the lifetime becomes inactive state, it will receive the latest data when becomes active again. For example, once in the background Activity will receive the latest data immediately after the return to the front desk.

 

(B) LiveData use

1. Create a stored instance of the ViewModel class LiveData

        We create a container MutableLiveData LiveData and type specified in the generic data. We usually do not directly access MutableLiveData, but create a getter method.

public class ViewModelWithLiveData extends ViewModel {
    private MutableLiveData<Integer> likedNumber;

//    public ViewModelWithLiveData() {
//        likedNumber = new MutableLiveData<>();
//        likedNumber.setValue(0);
//    }

    public MutableLiveData<Integer> getLikedNumber() {
        if (likedNumber == null) {
            likedNumber = new MutableLiveData<>();
            likedNumber.setValue(0);
        }
        return likedNumber;
    }

    public void addLikedNumber(int n) {
        likedNumber.setValue(likedNumber.getValue() + n);
    }
}

 2. Create an instance of the ViewModel, and get through the instance of the object MutableLiveData

 3. The observed change in the data by the method observe objects MutableLiveData

        The first parameter is a method observe LifecycleOwner , it must be an object having Lifecycle management function. The second argument to a Observer interface, and changes to data in its onChanged listening process. Once the data is changed, it will onChanged callback method.

public class Main2Activity extends AppCompatActivity {
    private ViewModelWithLiveData viewModelWithLiveData;
    private TextView textView;
    private ImageView likeBtn, disLikeBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        textView = findViewById(R.id.textView);
        likeBtn = findViewById(R.id.imageView1);
        disLikeBtn = findViewById(R.id.imageView2);

        viewModelWithLiveData = ViewModelProviders.of(this).get(ViewModelWithLiveData.class);
        viewModelWithLiveData.getLikedNumber().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                textView.setText(String.valueOf(integer));
            }
        });
        likeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModelWithLiveData.addLikedNumber(1);
            }
        });
        disLikeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModelWithLiveData.addLikedNumber(-1);
            }
        });
    }
}

 

Published 51 original articles · won praise 53 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34519487/article/details/104088457