如何管理并行和串行Retrofit API调用

时间:2018-02-22 04:48:45

标签: android rx-java observable retrofit2 rx-android

我在同一个活动中有4个API调用。其中3个是相互独立的。我想在前三个完成后拨打4号,我不确定每次执行前3个。我从数据库中获取数据然后它将调用。它可以是1个API调用,也可以是前三个中的2个或3个。 我试图顺序呼叫,但有时候在前3个完成之前开始4号。我的一些努力如下:

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 个答案:

答案 0 :(得分:6)

使用Rxjava2适配器和Retrofit然后你可以使用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 = {})

答案 1 :(得分:1)

声明一个大小为3的布尔数组,并将其索引初始化为false。在每个前三个API调用的onResponse方法中将索引更新为true。例如,为API调用1将索引0设置为true,依此类推。并检查onResponse方法,如果为true,则每个数组索引都为true,然后调用第四个API。

答案 2 :(得分:-1)

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

    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();
      }
    }
相关问题