Aliaksei
Aliaksei

Reputation: 1457

WebFlux & formation DTO

Hello recently started studying Webflux.

And sometimes I encounter the tasks that you need to form a simple DTO and return it Take for example the usual class dto

  @Data
  @Builder
  public static class Dto {

    private long id;
    private String code1;
    private String code2;
  }

And a primitive service with two methods...

  @Nullable Mono<String> getCode1(long id);
  @Nullable String getCode2(long id);

And wrote a method that forms at the output of Mono

  private Mono<Dto> fill(long id) {
var dto = Dto.builder()
    .id(id)
    .build();

//doOnNext
var dtoMono1 = service.getCode1(id)
    .map(code -> {
      dto.setCode1(code);
      return dto;
    })
    .doOnNext(innerDto -> innerDto.setCode2(service.getCode2(id)));

//map
var dtoMono2 = service.getCode1(id)
    .map(code -> {
      dto.setCode1(code);
      return dto;
    })
    .map(unused -> service.getCode2(id))
    .map(code -> {
      dto.setCode1(code);
      return dto;
    });

//just
var dtoMono3 = Mono.just(dto)
    .flatMap(innerDto -> service.getCode1(innerDto.getId()));

//just
var dtoMono4 = Mono.fromCallable(() -> dto)
    .subscribeOn(Schedulers.boundedElastic())
    .flatMap(innerDto -> service.getCode1(innerDto.getId()));
}

QUESTION:

  1. Is it possible to simply create DTO and use it in the Webflux call chain ... Or I need to wrap it in mono.just or mono.fromcallable (what are the pros and cons)
  2. How best to fill in values via doOnNext or through MAP. An extra line (Return DTO) appears in the case of MAP and some people also told me if for example NULL comes, doOnNext will miss it and go further to fill up current dto. But on the other, the MAP is used to transform the object, and the doOnNext is more for debugging and logging

Thanks you...

Upvotes: 0

Views: 201

Answers (1)

mslowiak
mslowiak

Reputation: 1838

How about using zip operator in such a case? I hope this example can help you:

private Mono<Dto> fill(long id) {
    return Mono.zip(someService.getCode1(id), Mono.just(someService.getCode2(id)))
            .map(tuple ->
                    Dto.builder()
                            .id(id)
                            .code1(tuple.getT1())
                            .code2(tuple.getT2())
                            .build()
            );
}

Upvotes: 1

Related Questions