Reputation: 561
I am a newbie in spring web flux.
I have an upstream service that doesn't supports batch calls, hence I'll have to call it multiple times for each object in my array. I also need instance of request parameters because the service doesn't return these attributes in it's response.
For example, This is the response I'll be sending to our clients
class Person {
int id;
String name;
int phoneNo;
}
and I have list of ids only
List<Integer> lstIds
Also for each person the api response is
{
"name": "name",
"phoneNo": 2222222222
}
Notice, there's no id field in the response hence, I'd need request parameter to map the request with response.
I have a method named createRequestFromIdWillReturnMono(int id)
that takes the integer id and returns the web client Mono as response.
What I've tried so far
List<Person> response = new ArrayList<Person>();
List<Integer> lstInt = IntStream.rangeClosed(0, 10).boxed().collect(Collectors.toList());
Flux
.fromIterable(lstInt)
.flatMap(i -> createRequestFromIdWillReturnMono(i)
.map(personResponse -> response.add(new Person(i, personResponse))));
return response;
But this code only runs the response.add call once, even though it calls the createRequestFromIdWillReturnMono 10 times.
How should I fix this?
Upvotes: 1
Views: 379
Reputation: 14712
You dont need the list, you can either use collectList
and return a list. Or you return the Flux<Person>
to the client, which is a stream.
Mono<List<Persons>> personsMono = Flux.fromIterable(lstInt)
.flatMap(i -> createRequestFromIdWillReturnMono(i))
.map(personResponse -> new Person(i,personResponse))
.collectList();
Something like this, im not at a computer now so cant ensure it compiles, but you should understand.
Upvotes: 1