问题
Per the example below from the LiveData Android documentation, what would be the RxJava 2 equivalent?
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...
}
回答1:
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);
Use createDefault
to have it with an initial value.
来源:https://stackoverflow.com/questions/49708853/what-is-the-mutablelivedata-equivalent-in-rxjava