Android 使用改进生成多个异步请求
在我的android应用程序中,我有一个屏幕,屏幕上有3个需要调整的微调器 从API调用填充Android 使用改进生成多个异步请求,android,api,retrofit,Android,Api,Retrofit,在我的android应用程序中,我有一个屏幕,屏幕上有3个需要调整的微调器 从API调用填充 static List<TripCode> tripCodeList = new ArrayList<>(); static List<Fleet> truckList = new ArrayList<>(); static List<Trailer> trailerList = new ArrayList<>(); 基本上,我删
static List<TripCode> tripCodeList = new ArrayList<>();
static List<Fleet> truckList = new ArrayList<>();
static List<Trailer> trailerList = new ArrayList<>();
基本上,我删除了setContentView(R.layout.activity\u create\u trip)代码>
从onCreate()
中,我调用了getTripCodes()
以下是getTripCodes()
public void getTripCodes(){
MyApplication.showProgressDialog(getString(R.string.please_wait)),这个;
IMyAPI IMyAPI=MyApplication.getIMyAPI();
Call Call=iMyAPI.getTripCodes();
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.issusccessful()&&response.body()!=null){
tripCodeList=response.body();
Log.d(“test”,“getTripCodes success=“+tripCodeList.size());
getTrucks();
}否则{
MyApplication.dismissProgressDialog();
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
MyApplication.dismissProgressDialog();
}
});
}
因此,在调用成功时,我调用另一个函数getTrucks()
,该函数也从API获得结果,在调用成功时,它将调用getTrailers()
但我认为这是浪费时间,因为我可以同时调用这三个函数,然后检查是否所有列表都已填充
但我不知道怎么做。如何检查所有呼叫是否成功?如果其中一个失败了,我怎么知道哪一个失败了呢?我相信对于您的问题,您可以很容易地使用具有协同程序支持的改进版2.6.0,您可以将所有函数声明为挂起函数,并使用async/launch
dispatcher进行调度,如果您想在某些情况下等待结果,请使用wait()
等待结果
并将RxJava/liveData用于响应式UI
您的示例代码如下所示
//maybe from Activity for ViewModel you can use ViewModelScope
GlobalScope.launch{
result1= async{ getTripCodes() }
result2= async{ getTrucks() }
result3= async{ getTrailers() }
doSomethingWithTripCodes(result1.await())
doSomethingWIthTrucks(result2.await())
doSomethingTrailers(result3.await())
}
参考:
我可以同时调用这三个函数,我想有很多方法。学习RxJava或多线程,如果使用Kotlin,则建议使用协同程序。
public void getTripCodes() {
MyApplication.showProgressDialog(getString(R.string.please_wait), this);
IMyAPI iMyAPI = MyApplication.getIMyAPI();
Call<List<TripCode>> call = iMyAPI.getTripCodes();
call.enqueue(new Callback<List<TripCode>>() {
@Override
public void onResponse(Call<List<TripCode>> call, Response<List<TripCode>> response) {
if (response.isSuccessful() && response.body() != null) {
tripCodeList = response.body();
Log.d("test", "getTripCodes success = " + tripCodeList.size());
getTrucks();
} else {
MyApplication.dismissProgressDialog();
}
}
@Override
public void onFailure(Call<List<TripCode>> call, Throwable t) {
MyApplication.dismissProgressDialog();
}
});
}
//maybe from Activity for ViewModel you can use ViewModelScope
GlobalScope.launch{
result1= async{ getTripCodes() }
result2= async{ getTrucks() }
result3= async{ getTrailers() }
doSomethingWithTripCodes(result1.await())
doSomethingWIthTrucks(result2.await())
doSomethingTrailers(result3.await())
}