How to check if Mono is empty?

后端 未结 3 1073
南旧
南旧 2021-01-31 16:11

I\'m developing a app with Spring Boot 2.0 and Kotlin using the WebFlux framework.

I want to check if a user id exits before save a transaction. I\'m stucked in a simple

3条回答
  •  离开以前
    2021-01-31 16:24

    Let me start by saying I am a newbie on reactive (java) and on this forum. I think you cannot really check in this code if a mono is empty because a mono represents code that will be executed later on, so in this code body you won't know yet if its is empty. Does that make sense?

    I just wrote something similar in Java which seems to work (but not 100% this is the best approach either):

        public Mono queryStore(ServerRequest request) { 
    
            Optional postalCode = request.queryParam("postalCode");                            
    
            Mono badQuery = ServerResponse.badRequest().build();
            Mono notFound = ServerResponse.notFound().build();
    
            if (!postalCode.isPresent()) { return  badQuery; }
    
            Flux stores = this.repository
                    .getNearByStores(postalCode.get(), 5);
    
            return ServerResponse.ok().contentType(APPLICATION_JSON)
                    .body(stores, Store.class)
                    .switchIfEmpty(notFound);
    }
    

提交回复
热议问题