rxjava中的重复执行或多次执行

时间:2018-12-17 14:52:43

标签: android kotlin rx-java2

我有一项特定的任务,可以通过多次调用同一请求从服务器获取几包数据。虽然答案包含 more 标志-我必须撤回该请求。

似乎是这样的:

fun getData(some params): Single<Response<DataEntity>>
//
repository.getData(params)
    .flatMap {
        if (it.body()?.more == false)
           more = false
        else (
          // here i want to repeat my request 
          // repository.getData(params) to get more data
        )
    }
    .flatMap {// here i want to get all the data from 
              //previous requests to save to db etc.
    }

也许我必须使用类似 repeatWhen repeautUntil 运算符的方法,但是我暂时找不到解决方案。请帮忙!)

1 个答案:

答案 0 :(得分:0)

您可以以递归方式使用concatMap运算符,并且作为退出条件仅返回结果:

Single<Response<DataEntity>> getDataAndContinue(params) {
  return getData(params)
      .concatMap(new Func1<Response<DataEntity>, Single<Response<DataEntity>>>() {

        @Override
        public Single<Response<DataEntity>> call(Response<DataEntity> response) {
          if (!response.body().hasMore()) {
            return Single.just(response);
          }
          return Single.just(response)
              .concatWith(getDataAndContinue(params));
        }   
    });
}
相关问题