Search code examples
rx-javareactive-programmingrx-androidreactivex

RxJava: How to to execute a task every 5 seconds only if the last task finished


I'm using RxJava. I have to execute a specific task every 5 seconds. That works perfectly by using the "Observable.Interval" method. However, I also have the following constraint: A new task must not be executed if the last task didn't finished. In this case, the new task need to be executed only when the last one finished.

I can't figure out how to do this simply with RxJava.

All ideas would be really appreciated ^^

Thanks for reading.


Solution

  • When you call interval a worker is selected that corresponds to a single thread from the given scheduler (default is computation):

    Observable
        .interval(5, TimeUnit.SECONDS)
        .flatMap(n -> task());
    

    or if nothing is returned by the task:

    Observable
       .interval(5, TimeUnit.SECONDS)
       .doOnNext(n -> task());
    

    This means that for every 5 seconds there will be a run but if the task takes 5 or more seconds then the tasks will be running continuously (but not concurrently).

    If you want to ensure a gap between running tasks then you could skip tasks based on the time of the finish of the last task. I can flesh that out if you need it.