Gregor
Gregor

Reputation: 3027

Flux Concatenation does not return

I'm experimenting with Spring Boot 2.0, webflux and reactiv Mongo repositories. I have two variants of first deleting and then adding data to a collection. In the first variant the thread blocks until the deletion is finished, in the second variant the adding of data is concatenated to the deletion.

Variant A

@GetMapping("init")
public String init() {
    Random rand = new Random();
    Flux<Power> powers = Flux.range(0, 10000)
            .map(i -> new Power(i,
                    LocalDateTime.now().toEpochSecond(ZoneOffset.of("+1")),
                    rand.nextDouble()));
    powerRepository.deleteAll().block();
    powerRepository.save(powers).blockLast();
    return "ok";
}

Variant B

@GetMapping("init")
public String init() {
    Random rand = new Random();
    Flux<Power> powers = Flux.range(0, 10000)
            .map(i -> new Power(i,
                    LocalDateTime.now().toEpochSecond(ZoneOffset.of("+1")),
                    rand.nextDouble()));
    powerRepository.deleteAll()
            .concatWith((v) -> powerRepository.save(powers)).blockLast();
    return "ok";
}

Variant A returns, variant B not. What is the difference? What is the right way to combine two repository operations?

Upvotes: 1

Views: 698

Answers (1)

gregturn
gregturn

Reputation: 2693

Chain using .then calls if nothing better. Avoid block calls and instead return Mono.just("ok").

public Mono<String> init() {
    return repo.deleteAll()
        .then(() -> repo.save(...))
        .then(() -> Mono.just("ok"));
}

Make the endpoint return Mono.

Upvotes: 3

Related Questions