Observable與Observer是RxJava2中最典型的一組觀察者與可觀察對象的組合。Observable 和 Observer 通過 subscribe() 方法實現訂閱關係,從而 Observable 可以在需要的時候發出事件來通知 Observer。
Observer接口中只有四個方法:
-
1、onSubscribe(@NonNull Disposable d)
在訂閱observable時回調,可以在這裏調用Disposable.dispose取消訂閱或者將Disposable對象保存起來以便在後續某個時刻取消訂閱(如activity.onDestory時)。 -
2、onNext(@NonNull T t)
在ObservableEmitter.onNext執行後回調,onNext表示的是整個響應鏈中的一環,在這裏處理響應鏈中的其中一個任務,可以多次調用。 但是一旦有onComplete 或者 onError調用,則事件隊列停止發射,Disposable.dispose。 -
3、onError(@NonNull Throwable e)
在ObservableEmitter.onError執行後或者鏈中任一環節出現異常時回調,表示任務執行失敗。 -
4、onComplete()
在ObservableEmitter.onComplete執行後回調,表示任務已全部完成,可以在這裏做收尾工作。onComplete與onError相斥,只可能出現其中一種回調。
Observer的使用注意事項:
1、方法調用順序模式是:
1)onSubscribe >> onNext >> (onError | onComplete)
2)onSubscribe >> onError 訂閱中出現錯誤2、不要多一個Observable被多個不同的Observer訂閱,否則在多線程併發中可能出現問題
3、Observer只能接收訂閱關係取消之前Observable發送的數據,對於訂閱關係取消之後Observable發送的數據,Observer將不會再接收。
Observer 源碼如下:
/**
* Provides a mechanism for receiving push-based notifications.
* 提供接收基於推送的通知的機制。
* <p>
* When an {@code Observer} is subscribed to an {ObservableSource} through the { ObservableSource#subscribe(IO_Reactivex_Observer)} method,
* 當一個Observer被訂閱爲observatesource通過訂閱者方法 ,
* <p>
* the {@code ObservableSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows disposing the sequence at any time,
* then the {@code ObservableSource} may call the Observer's {@link #onNext} method any number of times to provide notifications.
* ObservableSource可以在任何時間通知被觀察者狀態已改變,該{@code observatesource}可以調用觀察者的{@link\onNext}方法提供通知的次數不限。
* <p>
* A well-behaved {@code ObservableSource} will call an {@code Observer}'s {@link #onComplete} method exactly once or the {@code Observer}'s {@link #onError} method exactly once.
* 行爲良好的{@code observatesource}將準確地調用{@code Observer}的{@link}onComplete}方法一次,或者準確地調用{@code observator}的{@link}onError}方法一次。
*
* <p>
* Calling the {@code Observer}'s method must happen in a serialized fashion, that is,
* 調用{@code Observer}的方法必須以序列化的方式進行,也就是說,
* they must not be invoked concurrently by multiple threads in an overlapping fashion
* 他們一定不能同時被調用__ 被多線程用重疊的方式
* <p>
* and the invocation pattern must adhere to the following protocol:
* 並且調用模式必須 遵守以下規則:
* 順序模式是 onSubscribe >> onNext >> (onError | onComplete)
* <p>
* Subscribing an {@code Observer} to multiple {@code ObservableSource}s is not recommended.
* 不建議將一個觀察者訂閱到多個被觀察者上,容易造成混亂
* If such reuse happens, it is the duty of the {@code Observer} implementation to be ready to receive multiple calls to
* its methods and ensure proper concurrent behavior of its business logic.
* 如果發生了這樣的事情,有必要準備實現被多次調用方法,並且確保正確的併發業務邏輯
* <p>
* Calling {@link #onSubscribe(Disposable)}, {@link #onNext(Object)} or {@link #onError(Throwable)} with a null argument is forbidden.
* observable.subscribe(Observer observer)調用,使用一個null的參數是會被禁止的
* <p>
* <p>
* The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases
* 在實現onXXX時應該避免拋出運行時異常除了以下的原因,見鏈接中的文章
* (see <a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a> of the Reactive Streams specification反應流的規範):
*
* <li>If the argument is {@code null}, the methods can throw a {@code NullPointerException}.
* 如果observable.subscribe(Observer observer) 的參數是null,則會拋出一個 NullPointerException
* <p>
* Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no need to check for nulls in flows assembled from standard sources and intermediate operators.
* 請注意雖然Rxjava阻止空參進入流,因此通常是沒有檢查flows中null 的組裝標準來源和中間運營商
* <p>
* If there is a fatal error (such as {@code VirtualMachineError})如果有一個致命的錯誤,如VirtualMachineError
* <p>
* Violating Rule 2.13 results in undefined flow behavior. Generally, the following can happen:
* 違反規則2.13結果未定義流的行爲。一般來說,以下可能發生
* <p>
* 1、An upstream operator turns it into an {@link #onError} call,一個上游運營商把它轉爲一個onError 調用
* 2、If the flow is synchronous, the {ObservableSource#subscribe(IO_Reactivex_Observer)} throws instead of returning normally
* 如果flow是同步的, ObservableSource的subscribe()方法將被拋出而不是正常的返回
* <p>
* 3、If the flow is asynchronous, the exception propagates up to the component ({@Scheduler} or {@link java.util.concurrent.Executor})
* providing the asynchronous boundary the code is running and either routes the exception to the global
* 如果flow是異步的,除了通訊組件Scheduler 或者 Executor 提供正在運行的異步邊界代碼,或者其他的全局異常。
* 如拋出onError(Throwable)或者UncaughtExceptionHandler.uncaughtException(Thread, Throwable)
* {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} handler or the current thread's
* {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.</li>
* <p>
* From the {@code Observable}'s perspective,an {@code Observer} is the end consumer thus it is the {@code Observer}'s responsibility to handle the error case and signal it "further down".
* 從被觀察者的角度來看一個觀察者是最終的消費者,因此被觀察者有責任去處理error的原因並且給出 "further down"信號
* <p>
* This means unreliable code in the {@code onXXX} methods should be wrapped into `try-catch`es,specifically in {@link #onError(Throwable)} or {@link #onComplete()},
* and handled there (for example, by logging it or presenting the user with an error dialog)
* 這意味着在 onXXX中的不可靠的方法應該被try-catch包裹並處理它們( 如 打log日誌或者給一個錯誤提示對話框),特別是onError 和 onComplete中
* <p>
* However, if the error would be thrown from {@link #onNext(Object)}, <a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a> mandates
* 然而,如果error應該從onNext(Object)方法中被拋出,<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13 規定
* <p>
* the implementation calls {@link Disposable#dispose()} and signals the exception in a way that is adequate to the target context,
* 實現調用或者標記這個exception的方法應該 適合匹配上下文
* for example, by calling {@link #onError(Throwable)} on the same {@code Observer} instance.
* 例如:在同一個 Observer實例中調用onError(Throwable)方法
* <p>
* If, for some reason, the {@code Observer} won't follow Rule 2.13,the {@Observable#safeSubscribe(IO_Reactivex_Observer)} can wrap it with the necessary safeguards
* 處於一些原因不遵守Rule2.13, Observable.safeSubscribe(Observer)方法可以一些安全措施下使用,
* <p>
* and route exceptions thrown from {@code onNext} into {@code onError} and route exceptions thrown
* 並且route exceptions被從onNext 或者 onError拋出 ,或者被從onError和onComplete拋出的全局route exceptions處理通過
* from {@code onError} and {@code onComplete} into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}.
*
* @param <T> the type of item the Observer expects to observe 觀察者預計觀察的類型
* @see <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation: Observable</a>
*/
public interface Observer<T> {
/**
* Provides the Observer with the means of cancelling (disposing)
* 爲 Observer 提供了取消 連接Observable的同步和異步的兩種方法(從 onNext(Object)的內部方法中),
* the connection (channel) with the Observable in both synchronous (from within {@link #onNext(Object)}) and asynchronous manner.
*
* @param d the Disposable instance whose {@link Disposable#dispose()} can
* be called anytime to cancel the connection
* Disposable的實例對象可以通過dispose()隨時取消 觀察者和被觀察者直接的關係,放棄該次觀察
* @since 2.0
*/
void onSubscribe(@NonNull Disposable d);
/**
* Provides the Observer with a new item to observe.
* 爲觀察者提供了一個新的項目 去觀察
* <p>
* The {@Observable} may call this method 0 or more times.
* 被觀察者可能一次或多次調用該方法
* <p>
* The {@code Observable} will not call this method again after it calls either {@link #onComplete} or {@link #onError}.
* Observable調用了onComplete或者onError方法後將不再調用該方法,
*
* @param t the item emitted by the Observable 參數對Observable是可見的
*/
void onNext(@NonNull T t);
/**
* Notifies the Observer that the {Observable} has experienced an error condition.
* 通知觀察者,Observable發生了一個error condition
* <p>
* If the { Observable} calls this method, it will not thereafter call {@link #onNext} or {@link #onComplete}.
* 如果Observable調用了這個方法,在這之後將不再調用onNext 或者 onComplete方法
*
* @param e the exception encountered by the Observable Observable碰到的exception
*/
void onError(@NonNull Throwable e);
/**
* Notifies the Observer that the {Observable} has finished sending push-based notifications.
* 通知Observer, Observable已經完成了推送的消息
* <p>
* The {Observable} will not call this method if it calls {@link #onError}.
* Observable將不再調用這個方法,如果它調用過了onError方法
*/
void onComplete();
}
該篇博客純屬個人觀點和見解,如有錯誤懇請留言指正,萬分感激!
關聯鏈接: