我正在尝试使用RxJava实现以下逻辑:
以下解决方案部分解决了问题:
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;
}
是否有优雅的纯RxJava解决方案?
答案 0 :(得分:1)
其中一种更简单的方法是通过AsyncSubject
+比较和设置循环:
final AtomicReference<AsyncSubject<T>> subjectRef = new AtomicReference<>();
public Observable<T> get() {
for (;;) {
AsyncSubject<T> subject = subjectRef.get();
if (subject != null) {
return subject;
}
AsyncSubject<T> next = AsyncSubject.create();
if (subjectRef.compareAndSet(null, next)) {
Observable.just(1).map(ignored -> {
// your computation here
return 2; // the result
}).subscribeOn(Schedulers.io()).subscribe(subject);
return;
}
}
}
我差点忘了,更简单的方法是使用cache
:
Observable
.just(1)
.subscribeOn(Schedulers.io())
.map(ignored -> {
// computation here
return 2;
}).cache();