【问题标题】:flatMap reuse response from reactive callflatMap 重用响应式调用的响应
【发布时间】:2022-01-12 04:59:42
【问题描述】:

目前,我有一个问题,如下所示:

WebClient.call(...)
       .flatMap(user -> webclient.call("host1",user.getId/*obj request*/);})//assume this return X.class
  (*)  .flatMap(x -> webclient.call("host2",user.getName/*obj request*/))//"x" is not used here, i want reuse object "user" but was compiled error, // assume this return Y.class
       .map(x -> webclient.call(...))// "x" is used here

用户

Class User {
    string id;
    string name;
}

X

Class X {
    string deviceNo;
}

是

Class Y {
    Boolean isCorrect;
}

问题是我如何正确地重用上一次调用的“user”和“x”响应?

这是我对标记(*)位置的解决方案:

  1. 嵌套 flatMap(),然后可以返回(user) 用于下一个 map()。

到目前为止,当我构建这样的链(嵌套 flatMap...)时,变量(用户)的范围有什么问题吗?

       .flatMap(user -> { 
              return webclient.call("host1",user.getId/*obj request*/))
              .flatMap(x -> webclient.call("host2",user.getName/*obj request*/) //this consider as a side effect?
              .thenReturn(x));} still return "x"
       .map(x -> webclient.call(...))// "x" is used here 
  1. 通过使用地图将响应包装在对象中来保持响应(我不想使用此解决方案)
       .flatMap(user -> {
               return webclient.call("host1",user.getId/*obj request*/).map(x-> new X1(x, user)}))
       .flatMap(x1 -> webclient.call("host2", X1.GETUSER.GETNAME /*obj request*/).map(y -> new Y1(x1, y)}))
       .map(y1 -> webclient.call("host3",Y1.GETX1.X...))// "x" is used here 

X1,包装 x 和用户

Class X1 {
    public X1(x, user){}//contructor

    X x;
    User user
}

任何想法,请帮助审查/建议 谢谢

【问题讨论】:

  • 你在用Y对象做什么?

标签: java reactive-programming spring-webflux project-reactor flatmap


【解决方案1】:

这个问题很自以为是。

我个人会使用 zipWith 运算符,它将 2 个单声道的结果合并到一个元组中。

WebClient.call(...)
    .flatMap(user -> webclient.call("host1",user.getId())
            .zipWith(webclient.call("host2",user.getName()))
    .flatMap(values -> {
        var x = values.getT1();
        var y = values.getT2(),
    })
       

【讨论】:

  • 感谢您的回答,如果这种情况下我们使用“Y”响应作为下一个 flatMap 的 T2,我将其标记为已接受。还有一件事,先生。如果我们不需要 y(response from "host2") 并将其视为副作用,那么作为我的解决方案 1,我们如何正确使用它。
猜你喜欢
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
相关资源
最近更新 更多