How to get String from Mono in reactive java

前端 未结 6 1845
鱼传尺愫
鱼传尺愫 2020-12-09 04:01

I have a method which accepts Mono as a param. All I want is to get the actual String from it. Googled but didn\'t find answer except calling block() over Mono object but it

相关标签:
6条回答
  • 2020-12-09 04:29

    Finally what worked for me is calling flatMap method like below:

    public void getValue(Mono<String> monoString)
    {
       monoString.flatMap(this::print);
    }
    
    0 讨论(0)
  • 2020-12-09 04:30

    According to the doc you can do:

    String getValue(Mono<String> mono) {
        return mono.block();
    }
    

    be aware of the blocking call

    0 讨论(0)
  • 2020-12-09 04:34

    Better

    monoUser.map(User::getId) 
    
    0 讨论(0)
  • 2020-12-09 04:35

    Getting a String from a Mono<String> without a blocking call isn't easy, it's impossible. By definition. If the String isn't available yet (which Mono<String> allows), you can't get it except by waiting until it comes in and that's exactly what blocking is.

    Instead of "getting a String" you subscribe to the Mono and the Subscriber you pass will get the String when it becomes available (maybe immediately). E.g.

    myMono.subscribe(
      value -> Console.out.println(value), 
      error -> error.printStackTrace(), 
      () -> Console.out.println("completed without a value")
    )
    

    will print the value or error produced by myMono (type of value is String, type of error is Throwable). At https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html you can see other variants of subscribe too.

    0 讨论(0)
  • 2020-12-09 04:37

    What worked for me was the following:

    monoString.subscribe(this::print);

    0 讨论(0)
  • 2020-12-09 04:42

    Simplest answer is:

     String returnVal = mono.block();
    
    0 讨论(0)
提交回复
热议问题