Android - loop part of the code every 5 seconds

后端 未结 4 2021
醉酒成梦
醉酒成梦 2020-11-30 06:51

I would like to start repeating two lines of code every 5 seconds when I press the button START and end it, when I press the button STOP. I was trynig with a TimerTask and H

4条回答
  •  孤街浪徒
    2020-11-30 07:52

    You can use RxJava2/RxAndroid2 and create an Observable that emits a message every second (or whatever you want), example with pseudo code:

    Disposable timer = Observable.interval(1000L, TimeUnit.MILLISECONDS)
                .timeInterval()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer>() {
                    @Override
                    public void accept(@NonNull Timed longTimed) throws Exception {               
                        //your code here.
                        Log.d(TAG, new DateTime());
                    }
                });
    

    When you want to stop it, you can simply call:

    timer.dispose();
    

    I find this code much more readable than the other options.

提交回复
热议问题