Android封装一个通用的重试工具类

我们在做一些异步请求时,为了确保请求成功需要进行重试。
那么我们需要灵活的配置重试间隔时间,重试次数,还需要写个倒计时代码。
为此,本文使用rxjava为基础封装了一个工具类。
其中要注意的是内存泄漏问题,为此使用rxjava的周期组件AndroidLifecycleScopeProvider进行处理,如果非全局上下文需要在构造方法传入LifecycleOwner类。
下面直接上代码:

public class RetryForTimeDownHelper {
    private static final String TAG = "RetryForTimeDownHelper";

    /**
     * 重试次数
     */
    private volatile int retryCount;

    /**
     * 最大重试次数
     */
    private int maxRetryCount;

    /**
     * 重试时间
     */
    private long retryTimeMilli;
    private OnRetryCallBack onRetryCallBack;
    private LifecycleOwner lifecycleOwner;

    /**
     *
     * @param lifecycleOwner 非全局上下文需要传入,防止内存泄漏
     * @param maxRetryCount    最多重试次数
     * @param retryTimeMilli   重试间隔时间  单位毫秒
     * @param onRetryCallBack  重试回调:重试、重试结束处理结果
     */
    public RetryForTimeDownHelper(LifecycleOwner lifecycleOwner, int maxRetryCount, long retryTimeMilli, OnRetryCallBack onRetryCallBack) {
        this.lifecycleOwner = lifecycleOwner;
        this.maxRetryCount = maxRetryCount;
        this.retryTimeMilli = retryTimeMilli;
        this.onRetryCallBack = onRetryCallBack;
    }

    public RetryForTimeDownHelper(int maxRetryCount, long retryTimeMilli, OnRetryCallBack onRetryCallBack) {
        this(null, maxRetryCount, retryTimeMilli, onRetryCallBack);
    }

    public int getRetryCount() {
        return retryCount;
    }

    public void retry() {
        retryCount++;
        if (retryCount > maxRetryCount) {
            if (onRetryCallBack != null) {
                onRetryCallBack.onComplete();
            }
            return;
        }
        //非全局上下文需要传入,防止内存泄漏
        if (lifecycleOwner != null) {
            timeDownRetryLifecycle(lifecycleOwner);
            return;
        }
        //全局上下文中
        timeDownRetry();
    }

    private void timeDownRetry() {
        //倒计时3秒 重试
        Observable.timer(retryTimeMilli, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if (onRetryCallBack != null) {
                            onRetryCallBack.onNext();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable throwable) {
                        if (throwable != null) {
                            Log.e(TAG, "onError: ", throwable);
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void timeDownRetryLifecycle(LifecycleOwner lifecycleOwner) {
        //倒计时3秒 重试
        Observable.timer(retryTimeMilli, TimeUnit.MILLISECONDS)
                //AutoDispose 防止内存泄漏
                .as(AutoDispose.<Long>autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner)))
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if (onRetryCallBack != null) {
                            onRetryCallBack.onNext();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable throwable) {
                        if (throwable != null) {
                            Log.e(TAG, "onError: ", throwable);
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public interface OnRetryCallBack {
        /**
         * 调用重试
         */
        void onNext();

        /**
         * 处理结果
         */
        void onComplete();
    }
}


使用步骤

我们以登录为例

1、在调用登录时构造对象
public void login(){
//重试3次,间隔3秒重试
retryForTimeDownHelper = new RetryForTimeDownHelper(3, 3 * 1000, new RetryForTimeDownHelper.OnRetryCallBack() {
                @Override
                public void onNext() {
                    //重试登录
                    reLogin();
                }

                @Override
                public void onComplete() {
                    //处理登录失败结果
                    setFail();
                }
            });
   //登录的实现方法
   reLogin();
}

其中回调方法onNext()是进行重试的方法,onComplete()处理重试失败结果

2、在登录失败时调用下重试
    public void reLogin() {
        LoginHelper.getInstance().login(userId, token, new LoginCallBack(){
            @Override
            public void onFailed (String errorCode){
                if (retryForTimeDownHelper != null) {
                    retryForTimeDownHelper.retry();
                }
            }
            @Override
            public void onSuccess () {
                retryForTimeDownHelper = null;
            }
        }
    }

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。
在这里插入图片描述
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。

全套视频资料:

一、面试合集

在这里插入图片描述
二、源码解析合集
在这里插入图片描述

三、开源框架合集
在这里插入图片描述
欢迎大家一键三连支持,若需要文中资料,直接扫描文末CSDN官方认证微信卡片免费领取↓↓↓

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值