Spring Reactor - consuming Pageable endpoint

160 Views Asked by At

It's my first time working with Spring Reactor and I've faced the following challenge:

I have a service which allows to consume a number of records specified by page number and page size:

 Mono<GetContactsForGroupResponse> getContactsForGroup(Integer page, Integer size);

Among other fields GetContactsForGroupResponse contains pagination metadata:

class GetContactsForGroupResponse {
    private int totalPages;
    private int totalElements;
    private int numberOfElements;
    private int size;
    private int number;
    private boolean first;
    private boolean last;
    //.....
}

Now I need to write another method that would read all of the pages from

Mono<GetContactsForGroupResponse> getContactsForGroup(Integer page, Integer size);

and combine results into one single collection:

Mono<Collection<GetContactsForGroupResponse>> getContactsForGroup();

So far I've written:

            List<GetContactsForGroupResponse> groupContacts = new ArrayList<>();
            AtomicBoolean allPagesConsumed = new AtomicBoolean(false);

            int pageNumber = 0;
            int pageSize = 10;

            while(!allPagesConsumed.get()) {
                allPagesConsumed.set(true);
                GetContactsForGroupResponse getContactsForGroupResponse =
                        getContactsForGroup(accountId, g.getId(), 0, pageSize).block();
                Optional.ofNullable(getContactsForGroupResponse)
                        .ifPresent(r -> {
                            allPagesConsumed.set(r.isLast());
                            groupContacts.add(r);
                        });

                pageNumber ++;

I read results page by page until I reach the last page. I wonder what is the right way of implementation from SpringReactor point of view

Any advice would be appreciated,

Thanks

1

There are 1 best solutions below

0
On

there is no "right way", because this not a reactive question.

Since you are fetching "pages" you are dealing with a non reactive way of handling data. You have not disclosed anything about how you fetch this data, and from what type of database.

The easiest thing is to just make a query to the database and fetch everything in one go.

write a getAllContactsForGroup instead, and don't, do a while loop.