What is the MutableLiveData equivalent in RxJava?

别来无恙 提交于 2019-12-07 05:09:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!