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...
}
MutableLiveData. MutableLiveData is just a class that extends the LiveData type class. MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide.
By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers.
LiveData — the Architecture Components' counterpart to RxJava — is intrinsically lifecycle-aware. So, another option would be to have some sort of adapter that converts RxJava into LiveData .
The RxJava's approach to choose a thread during the subscription, not in time of the sending is much more appropriate. Actually the only advantage of LiveData over RxJava we have noticed is they automatically subscribe and unsubscribe on Activity life cycle events (or over android components implementing life cycle).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With