I have a class variable that is initialized be a network call.
A getter-like method is responsible for returning the value if initialized, or waiting the value to be initialized if the network call hasn't returned yet.
How to implement this with RxJava ?
Another solution is that instead of waiting, I could simply create a new network call in case the value is still not initialized, like so:
private String value;
public Observable<String> getValue() {
if (value != null) {
return Observable.just(value);
}
return getValueRemotely();
}
private Observable<String> getValueRemotely() {
...
}
but I would like to avoid multiple network calls to be done.
Any idea ?
onNext(): This method is called when a new item is emitted from the Observable. onError(): This method is called when an error occurs and the emission of data is not successfully completed. onComplete(): This method is called when the Observable has successfully completed emitting all items.
RxJava 2 introduced the concept of Disposables . Disposables are streams/links/connections between Observer and Observable . They're meant to give power to the Observers to control Observables . In most cases, the Observer is a UI element, ie; Fragment , Activity , or a corresponding viewmodel of those elements.
Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.
RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.
That's actually a good use-case for AsyncSubject
.
private AsyncSubject<String> value = AsyncSubject.create();
public Observable<String> getValue() {
value.asObservable();
}
And in getValueRemotely()
you have to ensure the calls to onNext()
and onComplete()
on value
.
value.onNext(valueString);
value.onCommpleted();
An AsyncSubject
observable emits one item only if it was completed.
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