简体   繁体   中英

Subscribing to an empty Flux causes an infinite loop

I have a call chain that looks something like this:

public ResponseEntity<Flux<Entity>> create() {
    return ResponseEntity.ok(saveList());
}

public Flux<Entity> saveList() {
    if(list.isEmpty()) return Flux.empty();
    return repository.saveAll(list);
}

Whether I return Flux.empty() directly or send it to the database call, if I add a .map() call onto the create() chain, it does not execute because there are no elements, as we would expect. However, if I add a .switchIfEmpty() , this also does not execute. No matter what combination of handlers I have tried for an empty Flux, it always results in an infinite loop, I assume because it's waiting for an element to be added so it can emit it.

The documentation suggests Flux.empty() should complete without emitting anything, but logging the Flux shows only onSubscribe() and request() are called, so it is not completing, hence why the. switchIfEmpty() is also not called.

What do I need to do to get an empty Flux to complete when I subscribe to it?

Any non-zero-sized Flux succeeds, but I have tried a number of different empty Flux types, such as from an array, which all fail.

I am using a hard-coded, non empty Publisher for switchIfEmpty() , since the implication seems to be that this is strictly necessary.

Since I have not received an answer (as usual, I might add) , I have created a workaround.

First, I collect the response in a list, then use Flux.error() and then complete the execution with onErrorComplete() in the caller.

public Flux<ListItem> create(List<ListItem> originalList) {
    return repository.get()
    .collectList()
    .flatMapMany(list -> {
        if(list.isEmpty()) return Flux.error(new IllegalStateException());
        return repository.saveAll(list);
    })
    .switchIfEmpty(repository.saveAll(originalList)
    .onErrorComplete();

Since my flatMapMany() relies on an initial database call, I additionally use switchIfEmpty() to catch any situation with an empty response. This does not necessarily fit every use case, but may be relevant for the types of problems that may result in an empty Flux.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM