更新:我正在使用 RxJava 1.x這是以下代碼段:private static void tryObservableToMap() { bad(); good();}private static void good() { System.out.println("GOOD CASE"); String goodOutput = m(m(m(m(m(Observable.from(ImmutableList.of("a","b","c","d")), "list") .distinct(), "distinct") .flatMap(s -> m(m(Observable.fromCallable(() -> getIntForString(s)).subscribeOn(Schedulers.io()), "getInt " + s) .map(intValue -> Pair.of(s, intValue)), "pair " + s)), "flatMap") .toMap(Pair::getKey, Pair::getValue), "toMap") .map(map -> map.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).collect(Collectors.joining("\n"))), "OUTER") .toBlocking() .first(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("\nOutput:"); System.out.println(goodOutput);}private static void bad() { System.out.println("BAD CASE"); String badOutput = m(m(m(m(Observable.from(ImmutableList.of("a","b","c","d")), "list") .distinct(), "distinct") .flatMap(s -> m(m(m(Observable.fromCallable(() -> getIntForString(s)).subscribeOn(Schedulers.io()), "getInt " + s) .map(intValue -> Pair.of(s, intValue)), "pair " + s) .toMap(Pair::getKey, Pair::getValue), "toMap " + s)), "flatMap") .map(map -> map.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).collect(Collectors.joining("\n"))), "OUTER") .toBlocking() .first(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("\nOutput:"); System.out.println(badOutput);}好與壞的區別在于,對于壞版本,我是.toMap在內部調用.flatMap而不是在.flatMap.如果您運行此代碼,您將看到作為執行一部分的所有 observable 的不同事件。我想知道為什么“外部”可觀察對象永遠不會因壞情況而終止。對RX有更深了解的人可以解釋一下嗎?
1 回答

慕田峪7331174
TA貢獻1828條經驗 獲得超13個贊
該RXLOG OUTER observable complete
丟失是因為有之間的競爭toBlocking().first()
和它上面完成的來源。它可能會過早取消訂閱,因此上面的源可能沒有機會發出onCompleted
. 在我的 i7 4770K 上,他們從不completed
為我打印。如果您替換first
為toIterable().iterator().next()
,它將提供必要的機會,您應該始終看到丟失的日志。
添加回答
舉報
0/150
提交
取消