Search code examples
javareactive-programmingspring-webfluxproject-reactor

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?

Solution

  • 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;
        });
    }