问题描述
根据 LiveData Android 文档中的以下示例,RxJava 2 的等效项是什么?
Per the example below from the LiveData Android documentation, what would be the RxJava 2 equivalent?
我们当然可以使用publish()
、refcount()
和replay()
的组合来实现MutableLiveData observable的核心行为.也就是说,mCurrentName.setValue()
的类似对应物是什么,因为它涉及检测变化并发出相应的事件?
We certainly can use a combination of publish()
, refcount()
and replay()
to achieve the core of the MutableLiveData observable behavior. That said, what would be the analogous counterpart of mCurrentName.setValue()
as it pertains to detecting a change and emitting the corresponding event?
public class NameViewModel extends ViewModel {
// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<String>();
}
return mCurrentName;
}
// Rest of the ViewModel...
}
推荐答案
您可以使用 BehaviorSubject
在某些级别上复制效果.
You could replicate the effects with BehaviorSubject
on certain levels.
如果你只是想通知观察者:
If you just want to notify observers:
BehaviorSubject<Integer> subject = BehaviorSubject.create();
subject.subscribe(System.out::println);
subject.onNext(1);
如果你想通知观察者总是在主线程上:
If you want to notify observers always on the main thread:
BehaviorSubject<Integer> subject = BehaviorSubject.create();
Observable<Integer> observable = subject.observeOn(AndroidSchedulers.mainThread());
observable.subscribe(System.out::println);
subject.onNext(1);
如果您希望能够从任何线程发出信号:
If you want to be able to signal from any thread:
Subject<Integer> subject = BehaviorSubject.<Integer>create().toSerialized();
Observable<Integer> observable = subject.observeOn(AndroidSchedulers.mainThread());
observable.subscribe(System.out::println);
subject.onNext(1);
使用 createDefault
给它一个初始值.
Use createDefault
to have it with an initial value.
这篇关于RxJava 中的 MutableLiveData 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!