处理Project Reactor中的数据的最佳方式

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

Best way to handle data in Project Reactor

问题

使用handleflatMap来处理项目反应器中的数据?

使用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有助于将两个操作结合在一起,即flatMapfilter

英文:

What is the best way to handle data in a project reactor?

using flatMap:

public Mono&lt;User&gt; flat() {
    return this.repository.findByName(&quot;Jeff&quot;)
      .flatMap(
        user -&gt; {
          user.setInfo(new UserInfo(&quot;Palo Alto/CA&quot;, &quot;Safari&quot;, &quot;h1alexbel/transformed&quot;));
          return Mono.just(user);
        }
      );
  }

handle:

public Mono&lt;User&gt; handle() {
    return this.repository.findByName(&quot;Jeff&quot;)
      .handle(
        (user, sink) -&gt;
          user.setInfo(
            new UserInfo(&quot;Palo Alto/CA&quot;, &quot;Safari&quot;, &quot;h1alexbel/transformed&quot;)
          )
      );
  }

or something else?

As far I understand, handle helps to combine 2 operations together: flatMap
and filter.

答案1

得分: 2

handle 最接近的类似物是 map(不是 flatMap)。你可以把它看作是 mapfilter 的组合。与 flatMap 不同,handlemap 都是同步函数。

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.

huangapple
  • 本文由 发表于 2023年2月8日 22:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386970.html
匿名

发表评论

匿名网友

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

确定