亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 toMap 的錯誤放置會導致 RXJava 出現問題?

為什么 toMap 的錯誤放置會導致 RXJava 出現問題?

森欄 2022-01-06 17:08:53
更新:我正在使用 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為我打印。如果您替換firsttoIterable().iterator().next(),它將提供必要的機會,您應該始終看到丟失的日志。


查看完整回答
反對 回復 2022-01-06
  • 1 回答
  • 0 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號