Kain Kain - 1 year ago 140
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 Source

That's actually a good use-case for AsyncSubject.

private AsyncSubject<String> value = AsyncSubject.create();

public Observable<String> getValue() {

And in getValueRemotely() you have to ensure the calls to onNext() and onComplete() on value.


An AsyncSubject observable emits one item only if it was completed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download