如何等待异步可观察完成
我正在尝试使用rxjava构建一个示例。该示例应协调一个 ReactiveWareService 和一个 ReactiveReviewService 重构 WareAndReview 复合体。
ReactiveWareService
public Observable<Ware> findWares() {
return Observable.from(wareService.findWares());
}
ReactiveReviewService: reviewService.findReviewsByItem does a ThreadSleep to simulate a latency!
public Observable<Review> findReviewsByItem(final String item) {
return Observable.create((Observable.OnSubscribe<Review>) observer -> executor.execute(() -> {
try {
List<Review> reviews = reviewService.findReviewsByItem(item);
reviews.forEach(observer::onNext);
observer.onCompleted();
} catch (Exception e) {
observer.onError(e);
}
}));
}
public List<WareAndReview> findWaresWithReviews() throws RuntimeException {
final List<WareAndReview> wareAndReviews = new ArrayList<>();
wareService.findWares()
.map(WareAndReview::new)
.subscribe(wr -> {
wareAndReviews.add(wr);
//Async!!!!
reviewService.findReviewsByItem(wr.getWare().getItem())
.subscribe(wr::addReview,
throwable -> System.out.println("Error while trying to find reviews for " + wr)
);
}
);
//TODO: There should be a better way to wait for async reviewService.findReviewsByItem completion!
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
return wareAndReviews;
}
鉴于我不想返回可观察量,我该如何等待异步可观察(findReviewsByItem)完成?