pixel
pixel

Reputation: 26441

Shuffle emissions of a Flux in Reactor?

I have a Flux and I would like to shuffle its emissions.

So for emissions:

1, 2, 3, ...

I would like to have:

32, 5, 9, ...

Is it possible in Reactor?

Upvotes: 0

Views: 426

Answers (2)

kerbermeister
kerbermeister

Reputation: 4211

Another more elegant way is to use Flux.generate() to emit a random value:

Random random = new Random();

Flux.generate(sink -> sink.next(random.nextInt(256)))
        .subscribe(System.out::println);

Upvotes: 0

Ricard Kollcaku
Ricard Kollcaku

Reputation: 1702

I don't think Reactor has a function that shuffles for you but there is one workaround you can do. If you want to keep the upper stream as it is,

Random random = new Random();
Flux.range(1,256)
    .flatMap(integer -> Flux.just(integer).delayElements(Duration.ofMillis(random.nextInt(256))))
    .subscribe(System.out::println);

}

If you need random elements:

Flux.range(1,256)
        .map(integer -> random.nextInt(256))
        .subscribe(System.out::println)

Upvotes: 2

Related Questions