I might have a possible solution as below. Though I feel like there can be a better way to implement it, but this works for now. Do suggest alternatives/improvements if you see ways to make this better:
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
public class Watchtower {
public static void main(String[] arg) throws Exception {
// Boilerplate for setup
System.out.println("Welcome to Watchtower");
class SuperHero {
public String name;
public long delay;
public SuperHero(String name, int delay) {
this.name = name;
this.delay = (long) delay;
}
}
Observable<Long> clock = Observable.interval(1, TimeUnit.SECONDS).take(14);
clock.subscribe(tick -> System.out.println(tick + " seconds: "));
List<SuperHero> jla = new ArrayList<>(Arrays.asList(
new SuperHero("Bruce", 2),
new SuperHero("Barry", 1),
new SuperHero("Clark", 2),
new SuperHero("Hal", 3),
new SuperHero("Arthur", 2),
new SuperHero("Diana", 3)
)
);
// Rxjava stuff starts form here:
Observable<SuperHero> jl = Observable.from(jla);
final long[] cumDelay = {0};
Observable<SuperHero> delays = jl
.doOnNext(s -> cumDelay[0] += s.delay)
.delay(s -> Observable.timer(cumDelay[0], TimeUnit.SECONDS));
Observable.zip(jl, delays, (s, d) -> s)
.doOnNext(s -> System.out.println(s.name + " just came..."))
.doOnCompleted(() -> System.out.println("Everybody came!"))
.subscribe();
// Just to have program remain alive and run on normal command line
Thread.sleep(15000);
}
}
The output it produces:
Welcome to Watchtower
0 seconds:
1 seconds:
Bruce just came...
2 seconds:
Barry just came...
3 seconds:
4 seconds:
Clark just came...
5 seconds:
6 seconds:
7 seconds:
Hal just came...
8 seconds:
9 seconds:
Arthur just came...
10 seconds:
11 seconds:
12 seconds:
Diana just came...
Everybody came!
13 seconds: