0

I am very new to RxJava so my question could be completely dumb, but I couldn't figure out how to do it.

So I have N jobs that implement the following interface

interface Worker {
  int interval();
  void job();
}

What I want to achieve is a timer-like functionality that calls these Workers job() function every time when interval() amount of time passed.

What I've tried so far

Observable.fromArray(worker1, worker2)
                .flatMap(worker -> Observable.just(worker).delay(worker.delay(), TimeUnit.SECONDS))
                .subscribe(Worker::job);

This worked fine, the jobs were executed asynchronously after the given time has passed.

But this only executed once. I understand I need to use the interval() operator somehow but couldn't wrap my head around it.

Thanks in advance

Bako
  • 313
  • 1
  • 15

1 Answers1

0

If i correctly understand your question, you need to do something like that:

Observable.fromArray(worker1, worker2)
    .flatMap { worker ->
        Observable.interval(worker.interval(), TimeUnit.SECONDS)
            .flatMap { Observable.just(worker).delay(worker.delay(), TimeUnit.SECONDS) }
     }
     .subscribe(Worker::job)

You should notice that in this implementation your worker.job() calls will going in unexpected order