Search code examples
javamonocallable

Is there a way to update a local variable through Mono.fromCallable()'s return value of an api inside a while loop?


I need to run GET requests multiple times until the return of the GET is an empty array. Currently I have been doing it with a global receivedAllApiData variable I update in getApiValues if it is an empty array. However I need to find a way to do this in the method locally. Is there a way the mono.fromCallable could change a local variable?

while (!receivedAllApiData && offsetAmount < MAX_REQUEST_FALLBACK) {
            int offset = offset;
            Mono.fromCallable(() -> Api.getApiValues(Id, offset, LIMIT, property))
                    .map(this::getApiValues)
                    .subscribe(this::buildStructure, this::ErrorCounter);
            offsetAmount += LIMIT;
        }

maybe there is a better way to run several calls?


Solution

  • Using an atomicBoolean you can update the value inside the map function as below.

           AtomicBoolean receivedAllApiData = new AtomicBoolean(false);
    
            while (!!receivedAllApiData.get() && offsetAmount < MAX_REQUEST_FALLBACK) {
                int offset = offsetAmount;
                Mono.fromCallable(() -> Api.getApiValues(Id, offset, LIMIT, property))
                        .map(listOfValues -> {
                            List<Values> nonNullListOfValues = CollectionUtils.isEmpty(listOfValues) ? emptyList() : listOfValues;
                            receivedAllApiData.set(nonNullListOfValues.isEmpty());
                            return nonNullListOfValues;
                        })
                        .subscribe(this::buildStructure, this::ErrorCounter);
                offsetAmount += LIMIT;
            }