Rx验证码倒计时

2018-04-23  本文已影响61人  zsgnaw
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();
}
上一篇下一篇

猜你喜欢

热点阅读