Issue
i'm trying to convert this method to an a reactive method
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public List<String> users () {
List<String> list= new ArrayList<>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
creatorsList.add(user);
}
return list;
}
I Have something like this but i don't know how to conver the ArrayList to return an Mono<List>
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public Mono<List<String>> usersReactive () {
List<Mono<String>> list= new ArrayList<List>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
list.add(user);
}
return list;
}
Solution
If you really want a Mono, then just wrap the value that you want to transport in it:
return Mono.just(creatorsList);
But I doubt you really want to return a list in a Mono. Usually, reactive endpoints returning a number of items would return a Flux
return Flux.fromIterable(creatorsList);
But since your MongoCursor
is already iterable (you use its iterator in an enhanced for-loop), you can stream the cursor directly to the flux. This saves you from collecting all items into a list first.
return Flux.fromIterable(cursor);
And finally, if you are trying to convert your application to be reactive, it is wise to use the Mongo driver with native support for reactive streams: https://docs.mongodb.com/drivers/reactive-streams/
Answered By - knittl
Answer Checked By - Mary Flores (JavaFixing Volunteer)