Difference of setValue() & postValue() in MutableLiveData

后端 未结 7 1667
故里飘歌
故里飘歌 2020-11-28 05:34

There are two ways that make change value of MutableLiveData. But what is difference between setValue() & postVa

7条回答
  •  死守一世寂寞
    2020-11-28 06:08

    This is not a direct answer to the above problem. The answers from Sagar and w201 are awesome. But a simple rule of thumb I use in ViewModels for MutableLiveData is:

    private boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }
    
    private MutableLiveData mutVal = new MutableLiveData<>(false);
    public LiveData getMutVal() { return this.mutVal;  }
    public void setMutVal(boolean val) {
        if (isMainThread()) mutVal.setValue(val);
        else mutVal.postValue(val);
    }
    

    Replace mutVal with your desired value.

提交回复
热议问题