Search code examples
spring-webfluxobjectmapperreactor

Getting a warning when use objectmapper in flux inappropriate blocking method call in java reactor


i am new to reactor, i tried to create a flux from Iterable. then i want to convert my object into string by using object mapper. then the ide warns a message like this in this part of the code new ObjectMapper().writeValueAsString(event). the message Inappropriate blocking method call. there is no compile error. could you suggest a solution.


        Flux.fromIterable(Arrays.asList(new Event(), new Event()))
                .flatMap(event -> {
                    try {
                        return Mono.just(new ObjectMapper().writeValueAsString(event));
                    } catch (JsonProcessingException e) {
                        return Mono.error(e);
                    }
                })
                .subscribe(jsonStrin -> {
                    System.out.println("jsonStrin = " + jsonStrin);
                });

Solution

  • I will give you an answer, but I don't pretty sure this is what you want. it seems like block the thread. so then you can't get the exact benefits of reactive if you block the thread. that's why the IDE warns you. you can create the mono with monoSink. like below.

            AtomicReference<ObjectMapper> objectMapper = new AtomicReference<>(new ObjectMapper());
            Flux.fromIterable(Arrays.asList(new Event(), new Event()))
                    .flatMap(event -> {
                        return Mono.create(monoSink -> {
                            try {
                                monoSink.success(objectMapper .writeValueAsString(event));
                            } catch (JsonProcessingException e) {
                                monoSink.error(e);
                            }
                        });
    
                    })
                    .cast(String.class) // this cast will help you to axact data type that you want to continue the pipeline
                    .subscribe(jsonString -> {
                        System.out.println("jsonString = " + jsonString);
                    });
    

    please try out this method and check that error will be gone.

    it doesn't matter if objectMapper is be a normal java object as you did. (if you don't change). it is not necessary for your case.