英文:
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<Integer>
you can do the following:
Mono<Integer> result = mono.map(value -> 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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论