0

I am trying to have a delete operation(r2dbc) using Webflux based on the condition as below, but switchIf empty is not working as expected. Specific Items are deleted successfully is getting printed always irrespective of filter condition satisfies or not.

Mono.just(cart).filter(cart1 -> CollectionUtils.isNotEmpty(cart1.getItems()))
    .flatMapMany(cartV->Flux.fromIterable(cartV.getCartItems())).flatMap(items -> deleteItemsByIdName(id, items))
    .then(Mono.just("Specific Items are deleted successfully")).log().switchIfEmpty(deleteAllItems(id).then(Mono.just("All Items are deleted successfully"))).log();

Kindly let me know, what I am missing here.. Or I need to change the logic completely?

sub
  • 527
  • 1
  • 7
  • 24

1 Answers1

1

Actually, switchIfEmpty works exactly like it should. The problem you have is caused by .then(Mono.just("Specific Items are deleted successfully")). then method sends a given Mono upon receiving the complete signal from upstream publisher. In other words, when your condition is not met, then the cart items are not converted to Flux and they are not deleted, but the message is logged anyway. Take a look at doOnNext and see if sth like that works:

Mono.just(cart)
                .filter(cart1 -> CollectionUtils.isNotEmpty(cart1.getItems()))
                .flatMapMany(cartV -> Flux.fromIterable(cartV.getCartItems()))
                .flatMap(item -> deleteItemsByIdName(id, item)
                        .doOnNext(res -> log.info("Item " + item + " has been removed"))
                )
                .switchIfEmpty(deleteAllItems(id).doOnNext(res -> log.info("All items have been removed")));
sawim
  • 1,032
  • 8
  • 18