如何从 Mono<String> 获取字符串在反应式Java中 [英] How to get String from Mono&lt;String&gt; in reactive java

查看:168
本文介绍了如何从 Mono<String> 获取字符串在反应式Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受 Mono 作为参数的方法.我想要的只是从中获取实际的字符串.谷歌搜索但没有找到答案,除了在 Mono 对象上调用 block() 但它会进行阻塞调用 所以想避免使用 block().如果可能,请建议其他方式.我需要这个 String 的原因是因为在这个方法中我需要用实际的 String 值调用另一个方法比如 print() .我知道这很容易,但我是响应式编程的新手.

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 will make a blocking call so want to avoid using block(). Please suggest other way if possible. The reason why I need this String is because inside this method I need to call another method say print() with the actual String value. I understand this is easy but I am new to reactive programming.

代码:

public String getValue(Mono<String> monoString) {
    // How to get actual String from param monoString
    // and call print(String) method
}

public void print(String str) {
    System.out.println(str);
}

推荐答案

最后对我有用的是调用 flatMap 方法,如下所示:

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

public void getValue(Mono<String> monoString)
{
   monoString.flatMap(this::print);
}

这篇关于如何从 Mono<String> 获取字符串在反应式Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆