考虑以下代码: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 expensivefinal 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 做到这一点?
1 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
发生这种情况是因为flatMap用于并发处理 observables 而您需要顺序。要解决这个问题,您只需要更改您的flatMaptoconcatMap以确保您的getCorrectSafeCombination方法中可观察的顺序流:
Maybe<Integer> getCorrectSafeCombination() {
return getPossibleCombinations()
.toObservable()
.flatMapIterable(combinations -> combinations)
//this one
.concatMap(combination -> tryToOpenSafeWithCombination(combination).toObservable()
.map(isCorrect -> new CombinationCheckResult(combination, isCorrect)))
.filter(result -> result.isCorrect)
.map(result -> result.combination)
.firstElement();
}
添加回答
举报
0/150
提交
取消