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

2017年9月7日更新:
Rxjava 中 onError 时 doOnTerminate 不调用的原因探索


显示隐藏加载框的功能大家可以看我的这篇文章深入理解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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值