Hari Rao
Hari Rao

Reputation: 3240

I want to add objects in Flux dynamically

I am very new to reactive programming in Spring WebFlux. Kindly excuse me for my ignorance here.

The below code is not adding the object EyeCare to the Flux eyeCares. I read about Flux.create, Flux.generate here that seem to be used to create Flux also I read this

private Flux<EyeCare> populateFakeData(Locale locale, int count){
    Flux<EyeCare>  eyeCares = Flux.empty();
    for(int i=0; i< count; i++){               
        eyeCares.concatWithValues(fakeDataService.generateEyeCare(locale));
    }
    return eyeCares;
}   
  1. Are Flux.create or Flux.generate the way I need to take to solve this?
  2. If yes then from where myEventProcessor came in the code snipped
  3. How can I bring in Flux.create or Flux.generate instead of eyeCares.concatWithValues?

Upvotes: 1

Views: 3101

Answers (2)

Martin Tarj&#225;nyi
Martin Tarj&#225;nyi

Reputation: 9947

To keep things simple, you can use range and map:

private Flux<EyeCare> populateFakeData(Locale locale, int count){
    return Flux.range(1, count)
            .map(i -> fakeDataService.generateEyeCare(locale));
}

Upvotes: 0

K.Nicholas
K.Nicholas

Reputation: 11551

You should be able to use Flux::generate pretty easily.

private Flux<EyeCare> populateFakeData(Locale locale, int count){
    return Flux.generate(()->new AtomicInteger(count), (state, sink) -> {
        if (state.getAndDecrement() > 0 ) {
            sink.next(generateEyeCare(locale));
        } else {
            sink.complete();
        }
        return state;
    });
}

Upvotes: 2

Related Questions