Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to repeat an observable every minute rxjava

I have the following method:

public class ParentalControlInteractor {
   public Single<Boolean> isPinSet() {
       return bamSdk.getPinManager().isPINSet();
   }
}

I want to call this function to run once, then repeat every minute until infinity but this seems clumsy:

    parentalControlInteractor.isPinSet()
            .subscribeOn(Schedulers.io())
            .repeat(10000)
            .timeout(1600,TimeUnit.MILLISECONDS)
            .doOnError(throwable -> {
                Timber.e(throwable,"Error getting if Pin is set");
                throwable.printStackTrace();
            })
            .subscribe(isPinSet -> {
                this.isPinSet = isPinSet;
                Timber.d("Pin is set = " + isPinSet.toString());
                });

Isn't there a better way to do it? I'm using RxJava2. Also, the method above only calls it 10000 times. I want to call it forever, like using Handler.postDelayed().

like image 372
Kristy Welsh Avatar asked Jul 28 '17 14:07

Kristy Welsh


2 Answers

you can use interval() oberator here is the code

DisposableObserver<Boolean> disposable = 
Observable.interval(1, TimeUnit.MINUTES)
            .flatMap(aLong -> isPinSet().toObservable())
            .subscribeOn(Schedulers.io())
            .subscribeWith({isPinSet -> doSomething()}, {throwable -> handleError()}, {});

if you want to finish this operation at any time call disposable.dispose()

like image 199
Mohamed Ibrahim Avatar answered Sep 28 '22 10:09

Mohamed Ibrahim


Try .repeatWhen(objectFlowable -> Flowable.timer(10, TimeUnit.SECONDS).repeat())

like image 37
vadimqa08 Avatar answered Sep 28 '22 10:09

vadimqa08