And*_*Dev 5 android kotlin rx-java
如何让我的视图模型在不使用回调并且实际不发送数据的情况下调用我的活动或片段中的函数。LiveData 用于将数据从视图模型发送到视图,但我没有数据。我只是想通知用户界面一些事情。这应该使用 RxJava 来完成还是太过分了?
LiveData 很好,这是我最近所做的(源自https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150)
首先创建一个类
public class OneTimeEvent {
private Boolean received;
public OneTimeEvent() {
received = false;
}
public Boolean receive () {
if (!received) {
received = true;
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的 ViewModel 中暴露你的事件
private MediatorLiveData<OneTimeEvent> eventListener = new MediatorLiveData<>();
public LiveData<OneTimeEvent> onEvent() {
return eventListener;
}
Run Code Online (Sandbox Code Playgroud)
现在你必须在 ViewModel 中的某个地方触发事件(就像其他事情已经完成一样)
eventListener.setValue(new OneTimeEvent()); //if its a background thread or callback use postValue!
Run Code Online (Sandbox Code Playgroud)
就是这样,现在您可以在您喜欢的任何活动或片段中观察 onEvent()
ViewModel.onEvent().observe(this, new Observer<OneTimeEvent>() {
@Override
public void onChanged(OneTimeEvent oneTimeEvent) {
if (oneTimeEvent.receive()){
// do something on event
}
}
});
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助,它的作用就像一个事件监听器,只是您可以同时从多个位置监听,并且每个事件只会被触发一次,例如,如果观察者重新连接到其他地方。
| 归档时间: |
|
| 查看次数: |
2208 次 |
| 最近记录: |