Android 如何管理并行和串行改装API调用

Android 如何管理并行和串行改装API调用,android,rx-java,observable,retrofit2,rx-android,Android,Rx Java,Observable,Retrofit2,Rx Android,我在同一活动中有4个API调用。其中3个是相互独立的。我想在前三个完成后打电话给4号,我不确定每次前三个的执行情况。我从数据库中获取数据,然后它将调用。它可以是1个API调用,也可以是前三个API调用中的2个或3个。 我试着按顺序一个接一个地打电话,但有时4号电话在前3号结束之前就开始了。我的一些努力如下: if(true){ // data 1 is available in database firstRetrofitCall(); }else{ //show no d

我在同一活动中有4个API调用。其中3个是相互独立的。我想在前三个完成后打电话给4号,我不确定每次前三个的执行情况。我从数据库中获取数据,然后它将调用。它可以是1个API调用,也可以是前三个API调用中的2个或3个。 我试着按顺序一个接一个地打电话,但有时4号电话在前3号结束之前就开始了。我的一些努力如下:

if(true){ // data 1 is available in database

    firstRetrofitCall();

}else{

    //show no data

}
if(true){ // data 2 is available in database

    secondRetrofitCall();

}else{

    //show no data

}
if(true){ // data 3 is available in database

    thirdRetrofitCall();

}else{

    //show no data

}

fourthRetrofitCall(); // I would like to execute this after first three finished

是否可以使用RxJava进行管理?声明大小为3的布尔数组,并将其索引初始化为false。在每个前三个API调用的onResponse方法中,将索引更新为true。例如,将API调用1的索引0设置为true,依此类推。并在onResponse方法中检查每个数组索引是否为true如果为true,则调用第四个API。

为每个调用添加一个布尔标志

    boolean isFirstExecuted;
    boolean isSecondExecuted;
    boolean isThirdExecuted;

    if(true){ // data 1 is available in database
        firstRetrofitCall();
    }else{
        isFirstExecuted = true;
    }
    if(true){ // data 2 is available in database
        secondRetrofitCall();
    }else{
       isSecondExecuted = true;
    }
    if(true){ // data 3 is available in database
        thirdRetrofitCall();
    }else{
        isThirdExecuted = true;
    }
    checkAndExceuteFourth();

    onFirstResponse(){
      isFirstExecuted = true;
      checkAndExceuteFourth(); 
    }

   onSecondResponse(){
      isSecondExecuted = true;
      checkAndExceuteFourth(); 
    }

   onThirdResponse(){
      isThirdExecuted = true;
      checkAndExceuteFourth(); 
    }
检查和执行第四种方法

 public void checkAndExceuteFourth(){
      if(isFirstExecuted && isFirstExecuted && isFirstExecuted ){
           fourthRetrofitCall();
      }
    }

使用Rxjava2适配器进行改装,然后可以使用Rxjava的zip操作符组合前三个调用,如下所示(假设调用分别返回X、Y、Z值,XYZwrapper只是这些值的容器),然后使用flatMap操作符进行第四个调用

Single.zip(
            firstRetrofitCall(),
            secondRetrofitCall(),
            thirdRetrofitCall(),
            Function3<X, Y, Z, XYZwrapper> { x, y, z -> return@Function3 XYZwrapper(x, y, z) }
        )
        .subscribeOn(Schedulers.io())
        .flatMap { XYZwrapper -> fourthRetrofitCall().subscribe() }//chaining 
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeBy( onError = {}, onSuccess = {})
Single.zip(
FirstCall(),
第二个调用(),
thirdRetrofitCall(),
函数3{x,y,z->return@Function3XYZwrapper(x,y,z)}
)
.subscribeOn(Schedulers.io())
.flatMap{XYZwrapper->fourthcall().subscribe()}//链接
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(onError={},onSuccess={})

请仔细阅读我的问题。不确定前3个是否都会被调用。是的,即使它们没有被调用,第四个仍然会执行,再次检查答案,如果第一个不应该被执行,那么它将立即在else中被标记为已执行