javaandroidrx-javarx-java2rx-java3

perform operation after each delay is complete in RxJava


I am trying to simulate the delay while emitting items in a specific sequence

Here I am trying to simulate the problem

List<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        integers.add(3);
        integers.add(4);
      

Disposable d = Observable
                    .just(integers)
                    .flatMap(integers1 -> {
                        return Observable
                                .zip(Observable.just(1L).concatWith(Observable.interval(10, 5, TimeUnit.SECONDS)),
                                     Observable.fromIterable(integers1), (aLong, integer1) -> {
                                            return new Pair<Long, Integer>(aLong, integer1);
                                        })
                                .flatMap(longIntegerPair -> {
                                    System.out.println("DATA " + longIntegerPair.getValue());
                                    return Observable.just(longIntegerPair.getValue());

                                })
                                .toList()
                                .toObservable();


                    })
                    .subscribe(integers1 -> {
                        System.out.println("END");
                    }, throwable -> {
                        System.out.println("Error " + throwable.getMessage());

                    });

The output of the above code is

DATA 1 
wait for 10 seconds
DATA 2
wait for 5
DATA 3
wait for 5
DATA 4
wait for 5 min

what I am expecting is to perform an operation once 10 seconds or 5 seconds delay is over at each stage but sure where do I inject that part in current flow.

DATA 1 
wait for 10 seconds
[perform operation]

DATA 2
wait for 5
[perform operation]

DATA 3
wait for 5
[perform operation]

DATA 4
wait for 5 min
[perform operation]

Solution

  • Use concatMap to make the sequence orderly and use delay to delay the processing of a data to get your printout pattern:

    Observable
    .zip(Observable.just(-1L).concatWith(Observable.interval(10, 5, TimeUnit.SECONDS)),
         Observable.range(1, 5), 
         (aLong, integer1) -> {
              return new Pair<Long, Integer>(aLong, integer1);
         }
    )
    .concatMap(longIntegerPair -> {
           System.out.println("DATA " + longIntegerPair.getValue());
           return Observable.just(longIntegerPair.getValue())
                   .delay(longIntegerPair.getKey() < 0 ? 10 : 5, TimeUnit.SECONDS)
                   .flatMap(value -> {
                       System.out.println("[performing operation] " + value);
                       return Observable.just(value);
                  });
    })
    .toList()
    .toObservable()
    .blockingSubscribe();