如何在响应式 Java 中从 Mono<String> 获取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47179937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get String from Mono<String> in reactive java
提问by nanosoft
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.
我有一个接受 Mono 作为参数的方法。我想要的只是从中获取实际的字符串。谷歌搜索但除了在 Mono 对象上调用 block() 之外没有找到答案,但它会进行阻塞调用,因此要避免使用 block()。如果可能,请建议其他方式。我需要这个 String 的原因是因为在这个方法中我需要用实际的 String 值调用另一个方法比如 print() 。我知道这很容易,但我是响应式编程的新手。
Code:
代码:
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);
}
采纳答案by nanosoft
Finally what worked for me is calling flatMap method like below:
最后对我有用的是调用 flatMap 方法,如下所示:
public void getValue(Mono<String> monoString)
{
monoString.flatMap(this::print);
}
回答by ΦXoc? ? Пepeúpa ツ
回答by Alexey Romanov
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.
String
在Mono<String>
没有阻塞调用的情况下从 a获取 a并不容易,这是不可能的。根据定义。如果String
尚不可用(Mono<String>
允许),则除非等待它进入,否则您无法获得它,而这正是阻塞。
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.
而不是“让String
”你subscribe
到Mono
,Subscriber
你通过的将String
在它变得可用时(可能立即)得到。例如
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.htmlyou can see other variants of subscribe
too.
将打印由myMono
(type of value
is String
, type of error
is Throwable
)产生的值或错误。在https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html您也可以看到其他变体subscribe
。
回答by AjayCodes
What worked for me was the following:
对我有用的是以下内容:
monoString.subscribe(this::print);
monoString.subscribe(this::print);
回答by Armen Arzumanyan
Better
更好的
monoUser.map(User::getId)