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

I have a class variable that is initialized by a network call.

The getter-like method is responsible for returning a value if it is initialized, or Waiting for a value to be initialized if the network call has not yet returned.

How to implement this using RxJava?

Another solution is that instead of waiting, I could just create a new network call if the value is still not initialized, for example:

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 some network calls.

Any idea?

+4
source share
2 answers

AsyncSubject.

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

public Observable<String> getValue() {
    value.asObservable();
}

getValueRemotely() onNext() onComplete() value.

value.onNext(valueString);
value.onCommpleted();

An AsyncSubject , .

+4

TL; DR - Observable:

Observable<String> value = Observable
    .defer(() -> Observable.just(getValueRemotely()))
    .cacheWithInitialCapacity(1);

... :

value.subscribe(v -> /*use value received from net*/);

: RxJava . , - , "return observable.get()" - , . . ,

, . RxJava 'return', . , , "".

, - - . Java , , . , : - , .

0

Source: https://habr.com/ru/post/1662087/


All Articles