我有2个改装电话,我需要制作A& B:
(A):返回一个ArrayList
(B):得到(A)的结果,它是一个ArrayList。 (B)遍历ArrayList并使用each来进行改进调用,并将结果数据组合成最终的ArrayList,发送给我的订阅者onNext()
我无法正确获取语法....例如我正在尝试返回arAllMedia,但我的代码要求我返回一个Observable。
ServiceFactory.createRetrofitService().getUserFollowing(sessionMgr.getAuthToken())
.flatMap(new Func1<UserSelfFollows, Observable<? extends ArrayList<Media.MediaData>>>() {
@Override
public Observable<? extends ArrayList<Media.MediaData>> call(UserSelfFollows userSelfFollows) {
//make second requests based on response from First request to get all Users
ArrayList<Media.MediaData> arAllMedia = new ArrayList<>();
for(UserSelfFollows.UserDataFollows user : userSelfFollows.userdata){
Response <ResponseBody> response ;
Call <ResponseBody> call;
try {
call = ServiceFactory.createRetrofitService().getMediaOfUser(user.id,sessionMgr.getAuthToken());
response = call.execute();
}catch(IOException ex){
return Observable.error(ex);
}
if (response.isSuccessful()) {
try {
String str = responseHelper.streamToString( response.body().byteStream());
Gson gson = new GsonBuilder().create();
Media media = gson.fromJson(str, Media.class);
arAllMedia.addAll(media.mediaData);
} catch (IOException e) {
return Observable.error(e);
}
} else {
return Observable.error( new Exception( responseHelper.getErrorString( response.errorBody().byteStream())) );
}
}
return Observable.just(arAllMedia);
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<Media.MediaData>>() {
@Override
public final void onCompleted() {
}
@Override
public final void onError(Throwable e) {
}
@Override
public final void onNext(ArrayList<Media.MediaData> arMedia) {
}
})
使用Maxim建议我在下面,但它不会编译:
ServiceFactory.createRetrofitService().getUserFollowing(sessionMgr.getAuthToken())
.flatMapIterable(new Func1<UserSelfFollows, Iterable<?>>() {
@Override
public Iterable<?> call(UserSelfFollows userSelfFollows) {
return userSelfFollows.userdata;
}
})
.concatMap(new Func1<UserSelfFollows.UserDataFollows, Observable<Media.MediaData>>() {
@Override
public Observable<Media.MediaData> call(UserSelfFollows.UserDataFollows user) {
return ServiceFactory.createRetrofitService().getMediaOfUser(user.id,sessionMgr.getAuthToken());
}
});
答案 0 :(得分:1)
你需要返回
Observable.just(arAllMedia)
答案 1 :(得分:0)
您可以使用List
展开flatMapIterable
,然后使用concatMap
依次触发请求,然后使用List
运算符将结果收回toList
:
ServiceFactory.createRetrofitService().getUserFollowing(sessionMgr.getAuthToken()
.flatMapIterable(userSelfFollows -> userSelfFollows.userdata)
.concatMap(user -> /*get & parse media; must return Observable<Media.MediaData>*/)
.toList()
...