Kain Kain - 9 days ago 5
Android Question

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 ?

Answer

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.