将API调用与RX Java结合 [英] Combining API calls with RX Java
问题描述
我是RXJava的新手,在理解如何将API调用的结果链接在一起方面遇到困难.
I'm new to RXJava and i'm having trouble understanding how to chain together the result of API calls.
我正在使用改造A和B进行两个API调用,它们都返回一个可观察到的对象列表.两个API调用都是独立的,所以我想同时进行,但要获得最终结果,我需要首先获取A的结果,做一些工作,然后将其与B的结果结合起来以填充我的列表适配器
I'm making two API calls using retrofit, A and B, which both return an observable List of objects. Both API calls are independent so I want to make both at the same time, but to achieve my final result, I need to first take the result of A, do some work, then combine that with the result of B to populate my list adapter.
- 进行API调用A
- 进行API调用B
- 取A的结果并创建结果X
-
获取B + X的结果并填充适配器
- Make API Call A
- Make API Call B
- Take A's result and create result X
Take Result of B + X and populate adapter
@GET("/{object_id}/object_a")
Observable<List<Object_A>> getObjectAList(
@Path("object_id") long object_id);
@GET("/{object_id}/object_b")
Observable<List<Object_B>> getObjectBList(
@Path("object_id") long object_id);
这是我迷上使用RX Java的地方.我可以接受api调用A的结果并做我的工作 但我不确定如何获取刚刚生成的结果,并将其与API调用B组合.
This is where I get lost trying to use RX java. I can take the result of api call A and do my work but I'm not sure how to take the result I just generated and combine it with API Call B.
aService. getObjectAList(object_a.getID())
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.main)
.subscribe(new Action1<List<Object_A>>() {
@Override
public void call(List<Section> sections) {
// Do Stuff Here...
// Now i need to take this result and combine it with API Call B...
}
});
我想同时进行两个API调用,但是我不确定如何链接在一起并组合API调用.任何帮助都是有益的.
I want to make both API calls at the same time, but i'm not sure how to chain together and combine API calls. Any help is appreciative.
推荐答案
像这样吗?
Observable
// make api call for A list and B list
.combineLatest(getObjectAList(), getObjectBList(), new Func2<List<Object_A>, List<Object_B>, Object>() {
@Override
public Object call(List<Object_A> o, List<Object_B> o2) {
// Do what you need to do in the background thread
List x = createX(o);
List y = createY(x, o2);
return y;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Object y) {
// UI thread, do what you need e.g. renders the list
mAdapter.setList(y);
}
});
小心替换适当的类型应该使您非常接近解决方案.
Taking care of replacing the proper types should bring you quite close to the solution.
这篇关于将API调用与RX Java结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!