Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava : How to wait for a value to be initialized by a previous subscription?

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 ?

like image 825
Kain Avatar asked Nov 27 '16 21:11

Kain


People also ask

What is onNext in RxJava?

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.

What is disposable in RxJava?

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.

What is Completable RxJava?

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.

Is RxJava deprecated?

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.


1 Answers

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.

like image 87
tynn Avatar answered Sep 19 '22 20:09

tynn