0

I know there is a function named "hasElements" on a Flux object. But it behaves a bit strange!

Flux<RoomBO> rooms=serverRequest.bodyToMono(PageBO.class).flatMapMany(roomRepository::getRooms);
return rooms.hasElements().flatMap(aBool -> aBool?ServerResponse.ok().body(rooms,RoomBO.class):ServerResponse.badRequest().build());
return ServerResponse.ok().body(rooms,RoomBO.class)

The second return statement can return the right things I need when the flux object is not empty,but the first return statement only returns a empty array,which likes "[]" in json.I don't know why this could happen!I use the same data to test.The only difference is that I call the hasElements function in the first situation.But I need to return badRequest when the flux object is empty. And the hasElements function seems to make my flux object empty,though I know it doesn't do this actually.

softgreet
  • 35
  • 3
  • well, I think since the data taken out from the flux object to know about whether it's empty or not, the flux object has become empty. I can use collect() to make use of the elements of the flux object and at the same time I can know the number of the elements. But this costs a lot when the data is big and seems so stupid for the requirement to know whether my flux object is empty! – softgreet Aug 02 '21 at 13:04

2 Answers2

0

well, finally I decide to call switchIfEmpty(Mono.error()) to throw an error and then I deal with the special error globally(Sometimes it's not suitable to use onErrorReturn or onErrorResume). I think this can avoid the collect operation in memory when meets big data. But it's still not a good solution for the global error handler can be hard to maintain. I'd expect someone to give a better solution.

softgreet
  • 35
  • 3
0

In your example you are transforming class Flux to class RoomBO, it is one of the reasons, why you get an empty array.

If you need to return the processed list of rooms, then, I think, collectList should be your choice. https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#collectList--

Flux<RoomBO> roomsFlux = serverRequest.bodyToMono(PageBO.class)
    .flatMapMany(roomRepository::getRooms);
return rooms
    .collectList()
    .flatMap(rooms -> !rooms.isEmpty() ? ServerResponse.ok().bodyValue(rooms) : ServerResponse.badRequest().build());
Andrey Novikov
  • 121
  • 1
  • 6