flatMap 重用来自反应式调用的响应

flatMap reuse response from reactive call

目前,我有一个问题,是这样的:

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;
}

Y

Class Y {
    Boolean isCorrect;
}

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

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

  1. nested flatMap(), then can thenReturn(user) for next 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. keep response by wrapping it in an object using map (i don't want to use this solution)
       .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
}

任何想法,请帮助review/advice 谢谢

这个问题很自以为是。

我个人会使用 zipWith 运算符将 2 个 monos 的结果合并到一个元组中。

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(),
    })