繁体   English   中英

SIngle RxJava如何提取对象

[英]SIngle RxJava how to extract object

我可以想到两种方法来从Single中获取价值

Single<HotelResult> 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<HotelResult> 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时需要获得结果的情况。

subscribe可以帮助您在Android应用程序中,例如在页面上显示结果,禁用make按钮等subscribe某些操作。

即使不建议阻止它(你应该订阅),在RxJava v2中阻塞的方法是blockingGet(),它会立即返回对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM