【发布时间】:2018-01-23 22:24:13
【问题描述】:
我有一个关于 Android 和 Retrofit 的新问题。我想知道在 Android Activity 上处理多个异步调用的正确方法是什么,每一个,onResponse 返回下一个调用使用的值,因为如果我理解得很好,调用在后台运行,这意味着如果调用没有完成你返回的值将是 null 直到你得到一个成功的响应。
我想用这样的东西来实现这一点(只是基础):
private List<SomeModel> mylist;
final Call<List<SomeModel>> call1 = client.getSomeValues1();
final Call<List<SomeModel2>> call2 = client.getSomeValues2();
call1.enqueue(new Callback<SomeModel>() {
@Override
public void onResponse(SomeModel> call, Response<SomeModel> response) {
if (response.isSuccessful()) {
// Set mylist to response.body()
mylist = response.body();
}
}
@Override
public void onFailure(Call<SomeModel> call, Throwable t) {
mylist = null;
}
});
call2.enqueue(new Callback<SomeModel2>() {
@Override
public void onResponse(SomeModel2> call, Response<SomeModel2> response) {
if (response.isSuccessful()) {
// Do something with my list and also with call2 response
if(mylist != null) {
for (SomeModel singleObject: mylist) {
// Do something with each object
}
}
}
}
@Override
public void onFailure(Call<SomeModel2> call, Throwable t) {
// Do something with fail call
}
});
与之前的示例类似,因为调用在后台运行,并且可能 call2 先完成,然后 mylist 值将为 null,因为 call1 尚未完成。
我还想将 call2 放在 call1 onResponse 中,但我觉得不对。不得不说,我还在学习中,我还挺菜鸟的。
那么,处理这个问题的正确原因是什么以及如何处理?谢谢。我希望我的问题可以理解。
【问题讨论】:
-
使用 RxJava 来管道 api 调用。
-
是的,当
call1.onResponse被调用时,将 call2 加入队列 -
感谢您的回答,@insa_c 您能解释一下如何使用 rxjava2 实现这一目标吗?
-
Kotlin chaining api calls using rxjava 查看本教程,它在 Kotlin 中,但你应该没问题。或者,您可以查看stackoverflow.com/questions/43355395/…