You can use Rx java & Rx Android by adding this dependency as below :
//Rx Java
implementation 'io.reactivex.rxjava2:rxjava:2.2.13'
//Rx Android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
checkout Here for the latest version.
You need an Observable like this :
private final Observable etaUpdateRepeatableObservable =
Observable
.interval(ETA_UPDATE_INTERVALS, TimeUnit.MINUTES)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.repeat();
just change ETA_UPDATE_INTERVALS
to your specific value.
You need a Disposable for subscribing to observable and to dispose it when required (Like onCleared() on ViewModels)
private Disposable etaUpdateDisposable;
You need a Consumer that your repeated logic would go there.
private final Consumer etaUpdateConsumer = o -> {
//Here you got the repeated logic
};
Now you can subscribe(Start repeating function) and dispose(stop) observable every time you need.
private void addEtaUpdateDisposable() {
if (etaUpdateDisposable == null) {
etaUpdateDisposable = etaUpdateRepeatableObservable.subscribe(etaUpdateConsumer);
}
}
private void disposeEtaUpdate() {
if (
etaUpdateDisposable != null &&
!etaUpdateDisposable.isDisposed()
) {
etaUpdateDisposable.dispose();
etaUpdateDisposable = null;
}
}