1

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

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

    ...
}

我希望能够在state更改(_state.setValue(newvalue)或被_state.postValue(newvalue)调用)时做出反应(例如,添加日志语句),并且我想在BaseViewModel.

我怎么做?

4

1 回答 1

1

然后

protected val state: LiveData<Boolean> = _state 

state实际上应该是 a whichMediatorLiveData注册_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)
    }
}
于 2018-12-16T17:01:10.917 回答