Rxjava interval 和take 操作符精准实现倒计时功能

package com.haegyeong.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class SplashActivity extends AppCompatActivity {

    private static final String TAG = SplashActivity.class.getSimpleName();
    private int count = 5;
    private Disposable mDisposable;
    private Observer observer;
    private TextView tv_time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        tv_time = ((TextView) findViewById(R.id.tv_time));

        observer = new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(String aLong) {
                tv_time.setText("倒计时" + aLong);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

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


        Observable.interval(0, 1, TimeUnit.SECONDS) //设置间隔执行
                .take(count + 1) //设置总共取的次数
                .map(new Function() {
                    @Override
                    public String apply(Long aLong) throws Exception {
                        long l = count - aLong;
                        return l + "";
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
//跳进主页
    public void jumpMain(View view) {
        startActivity(new Intent(SplashActivity.this, MainActivity.class));
        finish();
    }
}

你可能感兴趣的:(Rxjava interval 和take 操作符精准实现倒计时功能)