如果我有Observable<JsonOrderList>
。
JsonOrderList
定义如下:
public class JsonOrderList {
public List<Order> data;
public int currentCount;
public int currentPage;
public int pageCount;
}
下面定义的API:
Observable<JsonOrderList> orderApi.orderList(before, after, limit, state)
我想过滤/处理List<Order> data
,然后返回JsonOrderList
orderApi.orderList(before, after, limit, state){
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
//How to process List<Order> data
.subscribe(new Action1<JsonOrderList>() {
@Override
public void call(JsonOrderList rpOrderList) {
pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
pushErrorData(ID_GET_ORDER_LIST, throwable);
}
}));
编辑:
doOnNext(new Action1<JsonOrderList>() {
@Override
public void call(JsonOrderList jsonOrderList) {
//can i use rxjava operator replace loop
for(Order order : jsonOrderList.data){
order.setBuyer(goodsApi.getBuyer(order.getBuyerId));
}
}
})
goodsApi.getBuyer(id)请求服务器获取BuyerInfo
我可以使用rxjava运算符替换循环??
答案 0 :(得分:1)
使用.map
运算符:
orderApi.orderList(before, after, limit, state)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(new Func1<List<Order>, JsonOrderList>() {
@Override
public JsonOrderList call(List<Order> orders) {
JsonOrderList jsonOrderList = new JsonOrderList();
// ... do some stuff to fill jsonOrderList
return jsonOrderList;
}
})
.subscribe(new Action1<JsonOrderList>() {
@Override
public void call(JsonOrderList rpOrderList) {
pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
pushErrorData(ID_GET_ORDER_LIST, throwable);
}
});
编辑:
在进一步解释问题后,我建议您使用以下代码。
我建议你不要使用.filter(...)
运算符,因为它会改变你的流(你会在subscribe
中得到一个不同的对象。)
orderApi.orderList(before, after, limit, state)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Action1<JsonOrderList>() {
@Override
public void call(JsonOrderList jsonOrderList) {
//do something with jsonOrderList.data
}
})
.subscribe(new Action1<JsonOrderList>() {
@Override
public void call(JsonOrderList rpOrderList) {
pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
pushErrorData(ID_GET_ORDER_LIST, throwable);
}
});