在Rxjava+Retrofit 2中檢查網路連線和顯示載入框
阿新 • • 發佈:2019-02-09
上篇講到顯示隱藏載入框我們用的RxJava的doOnSubscribe()和doOnTerminate()。這裡我們檢查網路連線同樣是要在傳送網路請求前檢查,能不能也在doOnSubscribe()裡檢查呢,答案是:不能!
為什麼呢?因為doOnSubscribe()發生在subscribe()之前,所以假如在doOnSubscribe()中檢查沒有網路的時候unsubscribe()的話,並不起作用。
然後,我們再來看原始碼中的註釋,我發現Subscriber的onStart()方法是在Subscriber and Observable已經建立了連線,但是Observable還沒有發射資料的時候呼叫的,符合我們的場景。
/**
* This method is invoked when the Subscriber and Observable have been connected but the Observable has
* not yet begun to emit items or send notifications to the Subscriber. Override this method to add any
* useful initialization to your subscription, for instance to initiate backpressure.
*/
public void onStart() {
// do nothing by default
}
還有Subscriber中的unsubscribe()方法,它可以在onCompleted方法呼叫之前,取消中斷掉我們的訂閱即subscribe。
/**
* Stops the receipt of notifications on the {@link Subscriber} that was registered when this Subscription
* was received.
* <p>
* This allows unregistering an {@link Subscriber} before it has finished receiving all events (i.e. before
* onCompleted is called).
*/
void unsubscribe();
所以要想實現在傳送網路請求的時候檢查網路連線,我們只需自定義一個NetCheckerSubscriber,如下:
public abstract class NetCheckerSubscriber<T> extends Subscriber<T> {
private Context context;
public NetCheckerSubscriber(Context context) {
this.context = context;
}
@Override
public void onStart() {
super.onStart();
if (!new DeviceUtils(context).isHasNetWork()) {
if (!isUnsubscribed()) {
unsubscribe();
}
Toast.makeText(context, "請檢查網路連線後重試!", Toast.LENGTH_SHORT).show();
}
}
}
在onStart方法中檢查網路連線,沒有網路的話便取消訂閱。
Over ,that is all,Thank you!