Search code examples
spring-bootspring-webfluxfluxreactive

How to fetch the index number while doing a flatMap() on a Flux<String>


I have a code block as below

var x = Flux.just("A", "B", "C", "D");
        x.flatMap(y -> {
            System.out.println(y);
            return Mono.just(y);
        }).subscribe();

This successfully prints:

A
B
C
D

Is there a way I can print the index/record number as well in addition to the String value?

A - 1
B - 2
C - 3
D - 4

Solution

  • You can try index():

    x.index()
     .flatMap(y -> {
         System.out.println(y.getT2() + "-" + y.getT1());
         return Mono.just(y);
     })
     .subscribe();