【问题标题】:Why is onChanged not called when value changed in LiveData List?为什么在 LiveData 列表中更改值时不调用 onChanged?
【发布时间】:2019-03-01 16:59:20
【问题描述】:

上下文

使用MutableLiveData<List<Integer>> 保存值。当List 中的第一个值(为简洁起见,以第一个值为例)递增时,TextView 应在onChanged 中更新以显示List 中的第一个值。

目标

  • 增加List 中的第一个值
  • List 的第一项更改时更新TextView

问题

  1. 在点击Button 时,List 中的第一个值会递增,但不会调用MutableLiveData.onChanged(),这是为什么呢?
  2. MutableLiveData 是否只响应其setValue 方法?
  3. 这是否可以通过包含MutableLiveData 整数的List 来解决(即MutableLiveData<List<MutableLiveData<Integer>>,有问题,因为需要List 中的每个项目的侦听器)?
  4. 有没有更好的方法来实现目标?

代码

final MutableLiveData<List<Integer>> vals = new MutableLiveData<>();
List<Integer> intVals = new ArrayList<>();
intVals.add(0);
vals.setValue(intVals);

tv.setText("" + vals.getValue().get(0));

vals.observe(this, new Observer<List<Integer>>() {
    @Override
    public void onChanged(@Nullable List<Integer> integers) {
        int firstVal = integers.get(0);
        Log.d(TAG, "onChanged val " + firstVal);
        tv.setText("" + firstVal);
    }
});

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // first val in List is incremented but onChanged isn't called, why?
        int newVal = vals.getValue().get(0) + 1;
        vals.getValue().set(0, newVal);
        Log.d(TAG, "set val at index 0 to " + newVal);
    }
});

【问题讨论】:

    标签: java android android-livedata mutablelivedata


    【解决方案1】:

    LiveData Observable 的onChanged 方法仅在调用setValue()postValue().setValue() 之后才被调用,因为postValue() 应该从不同的线程调用(onClick 发生在主线程所以@ 987654327@ 可以)。 无论如何,使用下面的代码将为您提供所需的内容:

    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // first val in List is incremented but onChanged isn't called, why?
        List<Integer> temp = vals.getValue();
        if(temp!=null) // null-safety just in case....
        {
            int newVal = temp.get(0) + 1;
            temp.set(0, newVal);
            vals.setValue(temp);
            Log.d(TAG, "set val at index 0 to " + newVal);
        }
    }
    });
    

    【讨论】:

    • 我正在考虑重置 LiveDataList 值,但这似乎很浪费,但解决方案确实有效(比 List 中每个项目的侦听器要好得多)
    【解决方案2】:

    你应该调用 setValue 或 postValue 来更新 LiveData,否则它不会被观察到,主要是我希望你使用 postValue 因为 setValue 必须在主线程中调用

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多