我可以想到两种方法来从Single中获取价值
Single observableHotelResult =
apiObservables.getHotelInfoObservable(requestBody);
final HotelResult[] hotelResults = new HotelResult[1];
singleHotelResult
.subscribe(hotelResult -> {
hotelResults[0] = hotelResult;
});
要么
final HotelResult hotelResult = singleHotelResult
.toBlocking()
.value();
它写在文档中,我们应该避免使用.toBlocking方法.
那么有没有更好的方法来获得价值
解决方法:
当我们使用toBlocking时,我们立即得到结果.当我们使用subscribe时,结果是异步获得的.
Single observableHotelResult =
apiObservables.getHotelInfoObservable(requestBody);
final HotelResult[] hotelResults = new HotelResult[1];
singleHotelResult.subscribe(hotelResult -> {
hotelResults[0] = hotelResult;
});
// hotelResults[0] may be not initialized here yet
// println not show result yet (if operation for getting hotel info is long)
System.out.println(hotelResults[0]);
对于阻止案件:
final HotelResult hotelResult = singleHotelResult.toBlocking().value();
// hotelResult has value here but program workflow will stuck here until API is being called.
toBlocking有助于在“普通”代码中使用Observable时需要获得结果的情况.
订阅可以帮助您在Android应用程序中,例如在页面上显示结果,禁用make按钮等订阅中的某些操作.
标签:java,system-reactive,rx-java,rx-android
来源: https://codeday.me/bug/20190527/1164895.html