6

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...
}
nhoxbypass
  • 9,695
  • 11
  • 48
  • 71
Newbie
  • 7,031
  • 9
  • 60
  • 85

1 Answers1

10

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.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Is it ok to just use `create()` like this? This blog post makes it really scary on topic #2: https://medium.com/@jagsaund/5-not-so-obvious-things-about-rxjava-c388bd19efbc – Michel Feinstein Oct 17 '18 at 19:34