LiveDataReactiveStreams到MutableLiveData

时间:2019-06-07 11:08:45

标签: android android-databinding android-livedata

如何将值从LiveDataReactiveStreams发布到MutableLiveData?我想实现双向数据绑定到Switch(视图),并将“已检查”值从数据库传递到MutableLiveData以及从UI传递。 LiveDAtaReactiveStreams仅返回不可变的LiveData。

//ViewModel
public final MutableLiveData<Boolean> switchChecked = new MutableLiveData<>();

LiveData<Boolean> data = LiveDataReactiveStreams.fromPublisher(/* Flowable from DB */); //??


//xml
<Switch
  ...
  android:checked="@={viewModel.switchChecked}"
/>

1 个答案:

答案 0 :(得分:1)

尝试MediatorLiveData

//ViewModel
public final MediatorLiveData<Boolean> switchChecked = new MediatorLiveData<>();

public MyViewModel() {
    ...

    switchChecked.addSource(LiveDataReactiveStreams.fromPublisher(/* Flowable from DB */), value -> {
        switchChecked.setValue(value);
    });

    ...
}