基于可观察的

时间:2015-06-07 15:52:01

标签: android rx-java

结构:

api.vehicles()端点返回id列表。 api.driveState(int id)返回车辆的状态,其中id为参数。

我需要什么:

拨打.vehicles()。对于返回的id,在.driveState(id)端点上对每个id进行一次调用,并等待所有调用成功并一起返回状态列表。我们暂时忽略retrys()和网络故障。

我试过的是:

api.vehicles()
    .flatMap(vehicles -> merge(getVehicleStates(vehicles)))
    .toList()
    .doOnNext(driveStates -> {

    });

其中getVehicleStates()是:

private List<Observable<DriveState>> getVehicleStates(List<Vehicle> vehicles){
    List<Observable<DriveState>> states = new ArrayList<>();
    for (Vehicle vehicle : vehicles) {
        states.add(api.driveState(vehicle.getId()));
    }
    return states;
}

我认为更好的是.zip()函数。但是我不知道如何处理FuncN()方法:

api.vehicles()
        .flatMap(vehicles -> 
                zip(getVehicleStates(vehicles), new FuncN<DriveState>() {
                    @Override public DriveState call(Object... args) {
                        return null;
                    }
                }
        ));

PS:略有相似但未得到答复: Combining 'n' Observables of the same type (RxJava)

1 个答案:

答案 0 :(得分:0)

zip(Iterable, FuncN)运算符将压缩您的可观察量,并在Object.. args中提供所有这些结果。

您好像正在寻找所有DriveState的列表 - 这就是您在args中获得的内容。 documentation for varargs解释说,这实际上是一个Object数组,其构造方便地被...语法隐藏。

您可以使用zip获取所有DriveState的列表,如下所示:

zip(getVehicleStates(vehicles), new FuncN<List<DriveState>>() {
    @Override public List<DriveState> call(Object... args) {
        return Arrays.asList((DriveState[])args);
    }
}

当然,您可能希望对DriveState对象进行操作,并对它们或某些结果对象等而不是列表返回一些修改。

相关问题