1. 程式人生 > >Rxjava 優雅的實現簡訊驗證碼傳送

Rxjava 優雅的實現簡訊驗證碼傳送

廢話不多說直接上程式碼

private fun countDown() {
        btn_send_code_activity_login.isEnabled = false
        disPose = Flowable.intervalRange(0,
                120,
                0,
                1,
                TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext
{ btn_send_code_activity_login .text = String.format(getString(R.string.label_code_time), 120 - it) } .doOnComplete { btn_send_code_activity_login.isEnabled = true btn_send_code_activity_login.text
= getString(R.string.label_get_code) } .`as`(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this))) .subscribe() }

這裡利用intervalRange引數意思如下

 /**
     * Signals a range of long values, the first after some initial delay and the rest periodically after
. * <p> * The sequence completes immediately after the last value (start + count - 1) has been reached. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator signals a {@code MissingBackpressureException} if the downstream can't keep up.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code intervalRange} by default operates on the {@link Schedulers#computation() computation} {@link Scheduler}.</dd> * </dl> * @param start that start value of the range * @param count the number of values to emit in total, if zero, the operator emits an onComplete after the initial delay. * @param initialDelay the initial delay before signaling the first value (the start) * @param period the period between subsequent values * @param unit the unit of measure of the initialDelay and period amounts * @return the new Flowable instance */ @CheckReturnValue @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.COMPUTATION) public static Flowable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit) { return intervalRange(start, count, initialDelay, period, unit, Schedulers.computation()); }