Currently, I have a question, something like this:
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
User
Class User { string id; string name; }
X
Class X { string deviceNo; }
Y
Class Y { Boolean isCorrect; }
The question is how do I reuse correctly the “user” and the “x” response from the previous call?
Here are my solutions for marked(*) place:
- nested flatMap(), then can thenReturn(user) for next map().
Any issue with the scope of a variable(user) when I build a chain(nested flatMap…) like this so far?
.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
- 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, wrap x and user
Class X1 { public X1(x, user){}//contructor X x; User user }
any idea, please help to review/advice Thank you
Advertisement
Answer
This question is very opinionated.
i would personally use a zipWith operator which merges the results of 2 monos into a tuple.
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(), })