Rx验证码倒计时

private Disposable mDisposable;

private void getCode() {

        Observable.interval(1, TimeUnit.SECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .take(CODE_TIME).subscribe(new Observer() {

            @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验证码倒计时)