I would like to combine two observables: one is checking whether user is authorized to fetch data, the other one is for actual fetching the data, and I want to do the authorization parallel with fetching the data to reduce the total latency. Here is an example that is not parallel:
public static void main(String[] args) {
long startTime = currentTimeMillis();
Observable<Integer> result = isAuthorized().flatMap(isAuthorized -> {
if (isAuthorized) return data();
else throw new RuntimeException("unauthorized");
});
List<Integer> data = result.toList().toBlocking().single();
System.out.println("took: " + (currentTimeMillis() - startTime) + "ms");
System.out.println(data);
assert data.size() == 10;
}
private static Observable<Boolean> isAuthorized() {
return Observable.create( s -> {
try { sleep(5000); } catch (Exception e) {} // simulate latency
s.onNext(true);
s.onCompleted();
});
}
private static Observable<Integer> data() {
return Observable.create(s -> {
for (int i = 0; i < 10; i++) {
try { sleep(1000); } catch (Exception e) {} // simulate long running job
s.onNext(i);
}
s.onCompleted();
});
}
The total time to execute this is 15 seconds, if the calls to authorization and data fetching was parallel it should be 10 seconds. How to do that? Ideally I would also like to how many data items at most are cached in memory while waiting for authorization to complete.
BTW, I've read excellent answer about paralleling observables, but still don't now how to solve my problem.