鉴于以下链:
public Observable<List<PoiCollection>> findPoiCollectionsByUserId(Integer userId) {
return findUserGroupsByUserId(userId)
.flatMapIterable(
userGroups -> userGroups)
.flatMap(
userGroup -> findPoiCollectionToUserGroupsByUserGroupId(userGroup.getId()))
.flatMapIterable
(poiCollectionToUserGroups -> poiCollectionToUserGroups)
.flatMap(
poiCollectionToUserGroup -> {
Observable<PoiCollection> poiCollectionById = findPoiCollectionById(poiCollectionToUserGroup.getPoiCollectionId());
return poiCollectionById;
})
.toList()
.doOnNext(poiCollections -> {
Timber.d("poi-collections from DB:", poiCollections);
for(PoiCollection collection : poiCollections) {
Timber.d("collection:", collection);
}
})
.doOnError(throwable ->
Timber.e("error fetching poi-collections for user from DB"));
}
这是这样调用的:
Observable<List<PoiCollection>> fromDB = databaseHelper.findPoiCollectionsByUserId(id);
fromDB.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
poiCollections -> {
Activity activity = (Activity) getView();
Intent intent = new Intent(activity, PoiCollectionsActivity.class);
intent.putExtra("poi_collections", (Serializable) poiCollections);
activity.startActivity(intent);
activity.finish();
},
throwable -> {
if (throwable instanceof SocketTimeoutException) {
getView().showInternetDialog();
}
});
我发现自己想知道为什么doOnNext(...)
和doOnError(...)
都没有被调用。该链正在执行,直到toList()
,因此下面的行正在执行,之后就会停止。
poiCollectionToUserGroup -> {
Observable<PoiCollection> poiCollectionById = findPoiCollectionById(poiCollectionToUserGroup.getPoiCollectionId());
return poiCollectionById;
})
poiCollectionById
处的断点和findPoiCollectionById(...)
内的另一个断点清楚地显示,结果是从DB成功获取的结果!
那么,是什么阻止了doOnNext(...)
被调用?我明确地在观察者身上调用了subscribe(...)
。映射链一直运行到toList()
。我从未看到代码遇到doOnError(...)
,也没有遇到Action<Throwable>
的{{1}}部分。必须与subscribe(...)
有关。
答案 0 :(得分:0)
这不是我的问题的答案,而是我的问题的解决方案
public Observable<List<PoiCollection>> findPoiCollectionsByUserId(Integer userId) {
List<PoiCollection> poiCollections = new ArrayList<>();
findUserGroupsByUserId(userId)
.flatMap(Observable::from)
.flatMap(userGroup -> findPoiCollectionToUserGroupsByUserGroupId(userGroup.getId()))
.flatMap(Observable::from)
.flatMap(poiCollectionToUserGroup -> findPoiCollectionById(poiCollectionToUserGroup.getPoiCollectionId()))
.doOnNext(collection -> poiCollections.add(collection))
.subscribe();
return Observable.just(poiCollections);
}
我真的希望我不必创建ArrayList
,而是通过利用rxJavas collect(Collectors.toList())
来做类似Java 8 Stream API的toList()
方法。