Search code examples
spring-bootspring-webfluxfluxreactor

How to process comma separated string of ids using Mono<String>


I have a api which gives me a list of comma separated ids and I am using Spring Boot WebClient to make a call to the same and process the response.

The API response is [1,2,3,4] in plain/text (not json) and I am doing the following to process the results -

Mono<String> ids = client.get()
                .uri("http://localhost:8080")
                .retrieve()
                .bodyToMono(String.class);

I wanted to know how can I process the items inside the ids variable from thereon.

newbie to this api.


Solution

  • You could convert response directly into Flux, and process items one by one

    webClient.get()
            .uri("http://localhost:8080")
            .retrieve()
            .bodyToFlux(Integer.class)
            .doOnNext(id -> {
                System.out.println(id);
                // process id...
            })
            .subscribe();
    

    Another possible option is to convert Mono<String> into Flux<Integer> using method flatMapIterable:

    ids.flatMapIterable(line -> Arrays.asList(line.replace("[", "").replace ("]", "").split(",")))
            .doOnNext(id -> System.out.println(id))
            .subscribe();