嫌悪:
次のコードを考えてみます。
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);
}
私がオープンしたい、安全のための可能な「組み合わせ」(整数)のリストを受け取ります。唯一の1つの組み合わせはもちろんの正しいものです。
私の現在のアプローチでは、getCorrectSafeCombination()
それが最初に見つかった正しい組み合わせをお届けします。しかし、それにもかかわらず、すべての組み合わせをしようとします。
これは、効率的なかかわらずである:正しい組み合わせが発見されたとすぐに、他人をしようとする必要はありません。
どのようにこれは受信して行うことができますか?
ドミトリー:
ので、これは起こりflatMap
ますが、順次必要としながら、観測の同時処理のために使用されています。あなたは自分を変更する必要があることを修正するためにflatMap
するためにconcatMap
、あなたの中に観測の連続的な流れを確保するため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();
}