Home > Software design >  Refactor subscribe() to map()/flatMap() Spring Webflux
Refactor subscribe() to map()/flatMap() Spring Webflux

Time:02-25

I have this method and want to get rid of subscribe() (in line 5) and use map() or flatMap() instead (because it's not good to use subscribe() in a non-blocking scope):

private Mono<HttpStatus> transferToGlobalLibrary(UnpublishedArticle unpublishedArticle) {
    return updateArticleService.updateArticle(unpublishedToOutputContentAdapter.adaptUnpublishedArticle(unpublishedArticle))
                .map(httpStatusUpdateArticle -> {
                    if (httpStatusUpdateArticle.is2xxSuccessful())
                        articleRepository.save(unpublishedArticle).subscribe();
                    return httpStatusUpdateArticle;
                });
 }

I tried the following:

return updateArticleService.updateArticle(unpublishedToOutputContentAdapter.adaptUnpublishedArticle(unpublishedArticle))
                .map(httpStatusUpdateArticle -> {
                    if (httpStatusUpdateArticle.is2xxSuccessful())
                        return articleRepository.save(unpublishedArticle)
                                .flatMap(savedArticle -> httpStatusUpdateArticle);
                    return httpStatusUpdateArticle;
                });

which gives me the error no instance(s) of type variable(s) R exist so that HttpStatus conforms to Mono<? extends R>. Why is this error displayed?

What is the best way to refactor the code? Thanks!

Notes:

  • updateArticle() performs a REST API call, httpStatusUpdateArticle contains the resulting HttpStatus

CodePudding user response:

map is a method that returns a Mono.

When you return httpStatusUpdateArticle it's a Mono< HttpStatus>.

flatMap also returns a Mono. So when you return flatMap inside map, then map returns a Mono<Mono<HttpStatus>>.

One solution is to not call map in the first place:

return updateArticleService.updateArticle(unpublishedToOutputContentAdapter.adaptUnpublishedArticle(unpublishedArticle))
            .flatMap(httpStatusUpdateArticle -> {
                if (httpStatusUpdateArticle.is2xxSuccessful())
                    return articleRepository.save(unpublishedArticle)
                                            .map(savedArticle -> httpStatusUpdateArticle);
                return Mono.just(httpStatusUpdateArticle);
            });
  • Related