How can I convert a Stream of Mono to Flux

前端 未结 1 1404
日久生厌
日久生厌 2021-01-24 01:44

I have a method that try use WebClient to return a Mono

    @GetMapping(\"getMatch\")
    public Mono getMatch(@RequestParam Long matchId) {
               


        
                      
相关标签:
1条回答
  • 2021-01-24 02:27

    Probably, what you need is the following:

    @GetMapping("getMatches")
    public Flux<Object> getMatches(@RequestParam String matchesId) {
        List<Long> matchesList = JSON.parseArray(matchesId, Long.class);
        return Flux.fromStream(matchesList.stream())
                   .flatMap(this::getMatch);
    }
    

    Instead of:

    @GetMapping("getMatches")
    public Flux<Object> getMatches(@RequestParam String matchesId) {
        List<Long> matchesList = JSON.parseArray(matchesId, Long.class);
        return Flux.fromStream(matchesList.parallelStream().map(this::getMatch));
    }
    

    Notes:

    • Basically, you expect getMatches endpoint to return Flux<Object>. However, as it is written - it actually returns Flux<Mono<Object>>, therefore you see the strange output. To get Flux<Object>, I suggest, first, create Flux<Long> that are match ids, and then flatMap the result of calling getMatch (that returns Mono<Object>), this finally gives Flux<Object>.

    • Also, there is no need to use parallelStream(). Because you're already using reactor, everything will be performed concurrently on reactor scheduler.

    0 讨论(0)
提交回复
热议问题