0
votes

I'm relatively new to Spring WebFlux and Reactive programming in general, so please pardon my question is it doesn't make any sense.

I have a simple @PostMapping method that I'm trying to map a field in Mono to another chain method as such:

   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(50));
   }

    public String getRandomPlanetName() {
        Random rand = new Random();
        List<String> list = Stream.of(
                "Mercury",
                "Neptune")
                .collect(Collectors.toList());
        return list.get(rand.nextInt(list.size()));
    }

Basically what I want to achieve is to return a new Planet's name with "getRandomPlanetName()" and at the meantime setting a "delayElement" with a field in the Delay object. Something like this:

   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(delayBody.getDelayTime));
   }

Also, is it possible for me to return just a String, which is the result of getPlanetName() instead of a Mono of an object?

1

1 Answers

0
votes

Basically this looks into the Mono<Delay> for the delay time, and creates another Mono with this delayElement(delayTime).

@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> {
    return Mono.just(getRandomPlanetName())
        .delayElement(Duration.ofMillis(p.getDelayTime()));
  });
}

private String getRandomPlanetName() {
  Random rand = new Random();
  List<String> list = Arrays.asList("Mercury", "Neptune");
  return list.get(rand.nextInt(list.size()));
}

for better human readablity I put in the {}, you could also just write this:

@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> Mono.just(getRandomPlanetName()).delayElement(Duration.ofMillis(p.getDelayTime())));
}