I am trying to implement the following logic with RxJava:
- Execute server request if I don't have value locally
- Provide result to the subscriber
- If the request is running do not create a second one, but subscribe to the result of the running request.
The following solution partially solves the problem:
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private Observable<T> getValue(){
if(storage.getValue() == null) {
Future<T> futureValue = executor.submit(new Callable<T>() {
@Override
public T call() throws Exception {
return getValueFromStorageOrBackend();
}
});
return Observable.from(futureValue);
} else {
return Observable.just(storage.getValue());
}
}
private String getValueFromStorageOrBackend() {
final String currentValue = storage.getValue();
if (currentValue == null) {
Response response = backend.requestValue();
storage.setValue(response.getValue());
return response.getValue();
}
return currentValue;
}
Is there an elegant pure RxJava solution for this?