簡體   English   中英

如何在沒有 InterruptedException 的情況下處理 RxJava 中的處置

[英]How to handle dispose in RxJava without InterruptedException

在調用dispose()時截斷的以下代碼中,發射器線程被中斷( InterruptedException被拋出睡眠方法)。

    Observable<Integer> obs = Observable.create(emitter -> {
        for (int i = 0; i < 10; i++) {
            if (emitter.isDisposed()) {
                System.out.println("> exiting.");
                emitter.onComplete();
                return;
            }

            emitter.onNext(i);
            System.out.println("> calculation = " + i);


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        emitter.onComplete();
    });

    Disposable disposable = obs
            .subscribeOn(Schedulers.computation())
            .subscribe(System.out::println);

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    disposable.dispose();

從調試會話中,我看到中斷來自FutureTask ,它在處理過程中被取消。 在那里,根據運行線程檢查調用dispose()線程,如果不匹配,則中斷發射器。 由於我使用了計算Scheduler因此線程不同。

有什么辦法可以讓 dispose 不中斷這樣的發射器,或者實際上應該如何處理? 我在這種方法中看到的一個問題是,當我想要在調用onComplete()之前正常完成的可中斷操作(此處由 sleep 模擬onComplete()

請參閱2.0 中的不同之處 - 錯誤處理

2.x 的一項重要設計要求是不應吞下 Throwable 錯誤。 這意味着無法發出錯誤,因為下游的生命周期已經達到其終止狀態或下游取消了即將發出錯誤的序列。

因此,您可以將所有內容都包裝在 try/catch 中並正確發出錯誤:

Observable<Integer> obs = Observable.create(emitter -> {
   try {
      // ...
   } catch (InterruptedException ex) {
      // check if the interrupt is due to cancellation
      // if so, no need to signal the InterruptedException
      if (!disposable.isDisposed()) {
         observer.onError(ex);
      }
   }
});

或者設置一個全局錯誤消費者來忽略它:

RxJavaPlugins.setErrorHandler(e -> {
    // ..
    if (e instanceof InterruptedException) {
        // fine, some blocking code was interrupted by a dispose call
        return;
    }
    // ...
    Log.warning("Undeliverable exception received, not sure what to do", e);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM