android 监听多个 MutableLiveData 属性变化?

作者站长头像
站长
· 阅读数 7

android 监听多个 MutableLiveData 属性变化?

视图代码如下:

<Button 
   // ...
    android:text="@{vm.getText()}"
/>

java代码如下:

class TestVM extends ViewModel {
    private final MutableLiveData<Boolean> isRequest = new MutableLiveData<>();
    private final MutableLiveData<Integer> total = new MutableLiveData<>();

    public TestVM() {
        this.isReqeust.setValue(false);
         this.total.setValue(10);
    }

    public String getText() {
        if (this.isRequest.getValue()) {
            return "请求中";
        }
        int total = this.total.getValue();
        if (total >= 1000) {
            return '999+';
        }
        return String.valueOf(total);
    }
}

上述代码在 isRequesttotal 变化的时候,界面上显示的文本不更新,请问该怎么解决?

回复
1个回答
avatar
test
2024-06-28

用 MediatorLiveData:

class TestVM extends ViewModel {
    private final MutableLiveData<Boolean> isRequest = new MutableLiveData<>();
    private final MutableLiveData<Integer> total = new MutableLiveData<>();
    public final MediatorLiveData<String> text = new MediatorLiveData<>();

    public TestVM() {
        this.isRequest.setValue(false);
        this.total.setValue(10);

        text.addSource(isRequest, value -> text.setValue(getText()));
        text.addSource(total, value -> text.setValue(getText()));
    }

    private String getText() {
        if (this.isRequest.getValue()) {
            return "请求中";
        }
        int total = this.total.getValue();
        if (total >= 1000) {
            return "999+";
        }
        return String.valueOf(total);
    }
}

或者

TestVM viewModel = new ViewModelProvider(this).get(TestVM.class);

viewModel.isRequest.observe(this, new Observer<Boolean>() {
    @Override
    public void onChanged(Boolean isRequest) {
        updateButtonText();
    }
});

viewModel.total.observe(this, new Observer<Integer>() {
    @Override
    public void onChanged(Integer total) {
        updateButtonText();
    }
});

private void updateButtonText() {
    String text = viewModel.getText();
    myButton.setText(text); // 假设myButton是你的Button对象
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容