对于列表中的每个,执行操作直到满足条件

考虑以下代码:


void tryToOpenSafe() {

    getCorrectSafeCombination().subscribe(combination -> System.out.println("Correct combination is " + combination));

}


Maybe<Integer> getCorrectSafeCombination() {

    return getPossibleCombinations()

            .toObservable()

            .flatMapIterable(combinations -> combinations)

            .flatMap(combination -> tryToOpenSafeWithCombination(combination).toObservable()

                    .map(isCorrect -> new CombinationCheckResult(combination, isCorrect)))

            .filter(result -> result.isCorrect)

            .map(result -> result.combination)

            .firstElement();


}


Single<List<Integer>> getPossibleCombinations() {

    final List<Integer> combinations = Arrays.asList(123, 456, 789, 321);

    return Single.just(combinations);

}


// this is expensive

final Single<Boolean> tryToOpenSafeWithCombination(int combination) {

    System.out.println("Trying to open safe with " + combination);

    final boolean isCorrectCombination = combination == 789;

    return Single.just(isCorrectCombination);

}

我收到一份我想打开的保险箱的可能“组合”(整数)列表。当然只有一种组合才是正确的组合。


使用我目前的方法,getCorrectSafeCombination()将提供它找到的第一个正确组合;但它会尝试所有的组合。


但这很有效:一旦找到正确的组合,就无需尝试其他组合。


如何用 Rx 做到这一点?


临摹微笑
浏览 152回答 1
1回答

幕布斯6054654

发生这种情况是因为flatMap用于并发处理 observables 而您需要顺序。要解决这个问题,您只需要更改您的flatMaptoconcatMap以确保您的getCorrectSafeCombination方法中可观察的顺序流:Maybe<Integer> getCorrectSafeCombination() {&nbsp; &nbsp; return getPossibleCombinations()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toObservable()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMapIterable(combinations -> combinations)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //this one&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .concatMap(combination -> tryToOpenSafeWithCombination(combination).toObservable()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(isCorrect -> new CombinationCheckResult(combination, isCorrect)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(result -> result.isCorrect)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(result -> result.combination)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .firstElement();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java