LiveData

作者: 努力生活的西鱼 | 来源:发表于2020-11-18 20:43 被阅读0次

LiveData是一个可以感知Activity,Fragment生命周期的数据容器。

LiveData 需要结合ViewModel使用。
1. 我们将变量的类型修改为LiveData类型。

LiveData类型的变量需要我们通过set和get去赋值和取值。

public class LiveDataViewModel extends ViewModel {

    private final MutableLiveData<Integer> mCount = new MutableLiveData<>();

    public void setCountValue(int count) {
        this.mCount.setValue(count);
    }

    public LiveData<Integer> getCount() {
        return mCount;
    }

    public void add() {
        mCount.postValue(mCount.getValue() + 1);
    }

}
2. 数据变化的时候通知View
mLiveDataViewModel.getCount().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(Integer integer) {
        mLiveDataBinding.tvCount.setText(String.valueOf(integer));
    }
});
LiveData转换
Lifecycle提供了工具类Transformations来对LiveData的数据类型进行转换,可以在LiveData在数据返回给观察者之前修改LiveData中数据的具体类型,比如int型数字1,2等转换为中文大写壹,贰等,那么如何使用呢?
public class Main4ActivityViewModel extends ViewModel {

    private final MutableLiveData<Student> studentMutableLiveData = new MutableLiveData<>();

    public void setStudentMutableLiveData(Student studentMutableLiveData){
        this.studentMutableLiveData.setValue(studentMutableLiveData);
    }

    public LiveData<Student> getLiveData() {
        return studentMutableLiveData;
    }

    private LiveData<Integer> stuScore;

    public LiveData<Integer> getStuScore() {
        return stuScore;
    }
    
    public Main4ActivityViewModel() {
        stuScore = Transformations.map(studentMutableLiveData, new Function<Student, Integer>() {
            @Override
            public Integer apply(Student input) {
                return input.getStuScore();
            }
        });
    }

}
然后在Activity里面观察即可
private void observeData() {
    main4ViewModel.getLiveData().observe(this, new Observer<Student>() {
        @Override
        public void onChanged(Student student) {
            // main4Binding.tvStuscore.setText("分数: " + student.getStuScore());
        }
    });

    main4ViewModel.getStuScore().observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(Integer integer) {
            main4Binding.tvStuscore.setText("分数:" + integer);
        }
    });
}

相关文章

网友评论

      本文标题:LiveData

      本文链接:https://www.haomeiwen.com/subject/bvgvvktx.html