Imitate LiveData
behaviour, using RxJava's Subject
.
repositories {
jcenter()
}
dependencies {
implementation 'nolambda.stream:statesubject:1.0.0'
}
Simply change observe keyword, with subscribe
StateSubject<Integer> subject = new StateSubject()
subject.subscribe(lifecycleOwner, { item ->
// 1 and then 2
})
subject.postValue(1)
subject.postValue(2)
Removing observer is easy, rather than using removeObserver()
like LiveData
, StateSubject
return Disposable
in every subscribe event.
Disposable dispoasble = subject.subscribe(lifecycleOwner, this::renderData);
if(!dispoasble.isDisposed()){
dispoasble.dispose();
}
Since it use RxJava Subject
, manipulating stream is as easy as passing ObservableTransformer
.
StateSubject<String> subject = new StateSubject();
subject.subscribe(lifecycleOwner, s -> s.map(s -> s + "!"), s -> {
// Will trigger J! K! T! in sequence
})
subject.postValue("J");
subject.postValue("K");
subject.postValue("T");
Just replace extends LiveData<>
with extends StateSubject<>
public class StockLiveData extends StateSubject<BigDecimal> {
private StockManager stockManager;
private SimplePriceListener listener = new SimplePriceListener() {
@Override
public void onPriceChanged(BigDecimal price) {
setValue(price);
}
};
public StockLiveData(String symbol) {
stockManager = new StockManager(symbol);
}
@Override
protected void onActive() {
stockManager.requestPriceUpdates(listener);
}
@Override
protected void onInactive() {
stockManager.removeUpdates(listener);
}
}
Full parameters of subscribe()
@NonNull
public Disposable subscribe(@NonNull LifecycleOwner owner,
@Nullable ObservableTransformer<T, T> transformer,
@NonNull final Scheduler subscribeScheduler,
@NonNull final Scheduler observeScheduler,
@NonNull final Consumer<T> consumer)
You can jump to sample module or test files
- Add Immutable variant
MIT @ Esa Firman