获取来自Mono订阅调用的值

huangapple go评论67阅读模式
英文:

How to get value from a Mono subscribe call

问题

我有类似这样的东西:

mono.subscribe(val -> doSomething(val));

doSomething 返回一个整数。我想得到并返回该整数,或者一个 Mono<int>。我应该怎么做?

英文:

I have something like this:

mono.subscribe(val -> doSomething(val));

doSomething returns an integer. I would get and return that integer, or a Mono<int>. How can I do?

答案1

得分: 1

要返回 Mono<Integer>,你可以这样做:

Mono<Integer> result = mono.map(value -> doSomething(value));

但要记住,在Reactor中,直到订阅之前什么也不会发生,所以不要忘记订阅:

result.subscribe(System.out::println);

如果你想从Mono中获取一个整数,那么可以用block替换subscribe,但要注意这是一个阻塞操作:

Integer result = mono.map(App2::doSomething).block();
英文:

To return Mono&lt;Integer&gt; you can do the following:

Mono&lt;Integer&gt; result = mono.map(value -&gt; doSomething(value));

But remember that in Reactor, nothing happens until subscribe, so don't forget to subscribe:

result.subscribe(System.out::println);

If you want to get an integer out of mono, then you can replace subscribe with block, but pay attention that this is a blocking operation:

Integer result = mono.map(App2::doSomething).block();

huangapple
  • 本文由 发表于 2023年5月22日 21:41:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定