在Rxjava+Retrofit 2中检查网络连接和显示加载框

来源:互联网 发布:超星泛雅网络课程 编辑:程序博客网 时间:2024/06/06 08:46

显示隐藏加载框的功能大家可以看我的这篇文章深入理解RxJava的Side Effect Methods

上篇讲到显示隐藏加载框我们用的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!

0 0