在同一ViewModel中对LiveData更改做出反应

时间:2018-12-16 16:32:50

标签: kotlin android-livedata mutablelivedata

我的基础ViewModel由其他ViewModel个扩展:

abstract class BaseViewModel : ViewModel() {
    protected val _state = MutableLiveData<Boolean>()
    protected val state: LiveData<Boolean> = _state 

    ...
}

无论何时state发生更改(调用_state.setValue(newvalue)_state.postValue(newvalue)时,我都希望能够做出反应(例如,添加一条日志语句),并且我想在BaseViewModel内部进行操作。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

然后

protected val state: LiveData<Boolean> = _state 

state实际上应该是将MediatorLiveData注册为其来源的_state

final MediatorLiveData<T> mediator = new MediatorLiveData<>();
mediator.addSource(_state, new Observer<T>() {
    @Override
    public void onChanged(@Nullable T data) {
        // log here
        mediator.postValue(data);
    }
});
return mediator;

因此,在您的情况下,应该这样:

protected val state: LiveData<Boolean> = MediatorLiveData().also { mediator ->
    mediator.addSource(_state) { data ->
        // log here
        mediator.postValue(data)
    }
}