美文网首页
Rx验证码倒计时

Rx验证码倒计时

作者: zsgnaw | 来源:发表于2018-04-23 21:24 被阅读61次
    private Disposable mDisposable;
    
    private void getCode() {
    
            Observable.interval(1, TimeUnit.SECONDS).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .take(CODE_TIME).subscribe(new Observer<Long>() {
    
                @Override
                public void onSubscribe(Disposable d) {
                    mDisposable = d;
                    codeView.setClickable(false);
                    codeView.setText(CODE_TIME + "s");
                    // 请求验证码
                    mPresenter.getCode(phoneNumer);
                }
    
                @Override
                public void onNext(Long aLong) {
                    codeView.setClickable(false);
                    codeView.setRightText(CODE_TIME - aLong - 1 + "s");
                }
    
                @Override
                public void onError(Throwable e) {
                    getMsgCodeFailed();
                }
    
                @Override
                public void onComplete() {
                    getMsgCodeFailed();
                }
            });
        }
    
    // 验证码获取失败,清楚倒计时,重新可点击
    public void getMsgCodeFailed() {
        //停止继续发送
        if (mDisposable != null)
           mDisposable.dispose();
        codeView.setClickable(true);
        codeView.setText(获取验证码"");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null)
                mDisposable.dispose();
    }
    

    相关文章

      网友评论

          本文标题:Rx验证码倒计时

          本文链接:https://www.haomeiwen.com/subject/znkrlftx.html