英文:
Best way to handle data in Project Reactor
问题
使用handle
或flatMap
来处理项目反应器中的数据?
使用flatMap
:
public Mono<User> flat() {
return this.repository.findByName("Jeff")
.flatMap(
user -> {
user.setInfo(new UserInfo("Palo Alto/CA", "Safari", "h1alexbel/transformed"));
return Mono.just(user);
}
);
}
使用handle
:
public Mono<User> handle() {
return this.repository.findByName("Jeff")
.handle(
(user, sink) -> {
user.setInfo(new UserInfo("Palo Alto/CA", "Safari", "h1alexbel/transformed"));
sink.next(user);
}
);
}
或者还有其他方法?
据我理解,handle
有助于将两个操作结合在一起,即flatMap
和filter
。
英文:
What is the best way to handle data in a project reactor?
using flatMap:
public Mono<User> flat() {
return this.repository.findByName("Jeff")
.flatMap(
user -> {
user.setInfo(new UserInfo("Palo Alto/CA", "Safari", "h1alexbel/transformed"));
return Mono.just(user);
}
);
}
handle:
public Mono<User> handle() {
return this.repository.findByName("Jeff")
.handle(
(user, sink) ->
user.setInfo(
new UserInfo("Palo Alto/CA", "Safari", "h1alexbel/transformed")
)
);
}
or something else?
As far I understand, handle
helps to combine 2 operations together: flatMap
and filter
.
答案1
得分: 2
handle
最接近的类似物是 map
(不是 flatMap
)。你可以把它看作是 map
和 filter
的组合。与 flatMap
不同,handle
和 map
都是同步函数。
map
- 通过应用同步函数来转换发射的项目。它提供了1:1的映射,每个项目都应该被映射。跳过项目的唯一方法是抛出异常,然后立即使用 onErrorResume
处理错误信号。
handle
- 更灵活,提供0或1的映射。可以通过不发出信号来跳过项目,使用 sink.next()
。
在你的情况下,没有必要将用户包装为 Mono
并使用 flatMap
。使用 map
,因为映射是1:1。
英文:
The closest analog of the handle
is a map
(not flatMap
). You could think about it as a combination of the map
& filter
. In contrast to flatMap
both handle
and map
are synchronous function.
map
- transforms the emitted item by applying a synchronous function. It provides 1:1 mapping and every item should be mapped. The only way to skip item is to throw exception and then immediately handle the error signal using onErrorResume
.
handle
- is more flexible and provides 0 or 1 mapping. It's possible to skip items by not emitting signal using sink.next()
.
In your case there is no reason to wrap user into Mono
and use flatMap
. Use map
because mapping is 1:1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论