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
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.