2

现在我使用嵌套循环ReplaySubject来获取多个可观察对象,这需要在不使用任何循环的情况下进行转换,只使用可观察对象。

private Observable<BaseUnit> getUnitObservables(ArrayList<Map<Integer, Integer>> list, ReplaySubject<BaseUnit> subject) {

    ArrayList<Observable<BaseUnit>> observables = new ArrayList<>();
    
    for (Map<Integer, Integer> elem : list) {
        for (MapOperationName operationName : MapOperationName.values()) { // MapOperationName type is enum

            Observable<BaseUnit> observable = Observable.fromCallable(() -> {
                // some operations here

                subject.onNext(unit);
                observables.add(observable);
            });
        }
    }
    return Observable.merge(observables);
}

" Map<Integer, Integer> elem : list" 有 3 个元素。" MapOperationName.values()" 返回 7 个元素。所以我在上面的例子中完全应该是 21 岁。

试图重构这样的东西,但只得到 3 个元素:

private Observable<BaseUnit> getUnitObservables(ArrayList<Map<Integer, Integer>> list, ReplaySubject<BaseUnit> subject) {

    Observable<ListOperationName> observableOperation = 
    Observable.fromArray(MapOperationName.values());
    Observable<List<Integer>> observableList = Observable.fromIterable(list);
    return Observable.zip(observableList, observableOperation, (listElem, operationElem) -> {

        subject.onNext(unit);
        //some operations here
    });

}

如何正确组合ArrayListEnum获得全套配对组合?

4

2 回答 2

3

您可以将需要执行的操作嵌套在 aflatMap中以实现此目的:

private Observable<BaseUnit> getUnitObservables(ArrayList<Map<Integer, Integer>> list, ReplaySubject<BaseUnit> subject) {

    Observable<ListOperationName> observableOperation = 
        Observable.fromArray(MapOperationName.values());
    Observable<List<Integer>> observableList = Observable.fromIterable(list);
    return observableList
        .flatMap(listElem -> observableOperation
            .map(operationElem -> {
                // some operations here
                subject.onNext(unit);
                return unit;  // Assuming unit is a BaseUnit
            })
        );
}
于 2020-07-20T14:31:23.780 回答
1

我不喜欢将 a 传递ReplaySubject给您的方法。相反,您可以将您的方法作为来源并让您subject订阅它:

private Observable<BaseUnit> getUnitObservables(ArrayList<Map<Integer, Integer>> list) {
    return Observable.fromIterable(list)
            .flatMap(listElem -> Observable.fromArray(MapOperationName.values())
                    .map(operationElem -> {
                        // some operations here
                        return new BaseUnit();
                    })
            );
}

...
...

Subject<BaseUnit> subject = ReplaySubject.create();
subject
        .mergeWith(getUnitObservables(listParam))
        .subscribe();

于 2020-07-20T14:56:15.840 回答