0

I'm learning reactive programming with Reactor and I want to implement registration scenario where a user can have many accounts assigned to the same profile. However the username assigned to the profile and the phone assigned to the account must be unique.

As you can see in the following snippet, this scenario will be easy to implement if Reactor was offering the operator switchIfNotEmpty.

public Mono<PersonalAccountResponse> createPersonalAccount(PersonalAccountRequest request) {
    return Mono
            .just(request.isAlreadyUser())
            .flatMap(isAlreadyUser ->  {
                if(isAlreadyUser){
                    return profileDao
                            .findByUsername(request.getUsername()) //
                            .switchIfEmpty(Mono.error(() -> new IllegalArgumentException("...")));
                }else{
                    return profileDao
                            .findByUsername(request.getUsername())
                            .switchIfEmpty(Mono.from(profileDao.save(profileData)))
                            .switchIfNotEmpty(Mono.error(() -> new IllegalArgumentException("...")));
                }
            })
            .map(profileData -> personalAccountMapper.toData(request))
            .flatMap(accountData -> personalAccountDao
                                            .retrieveByMobile(request.getMobileNumber())
                                            .switchIfEmpty(Mono.from(personalAccountDao.save(accountData)))
                                            .switchIfNotEmpty(Mono.error(() -> new IllegalArgumentException("..."))))
            .map(data ->  personalAccountMapper.toResponse(data, request.getUsername()));
}

How can I implement this requirement without switchIfNotEmpty?

Thanks

nanachimi
  • 311
  • 3
  • 18

1 Answers1

1

To propagate an exception when a publisher emits a value, you can use one of several operators that operate on emitted values.

Some examples:

fluxOrMono.flatMap(next -> Mono.error(new IllegalArgumentException()))
fluxOrMono.map(next -> { throw new IllegalArgumentException(); })
fluxOrMono.doOnNext(next -> { throw new IllegalArgumentException(); })
fluxOrMono.handle((next, sink) -> sink.error(new IllegalArgumentException()))
Phil Clay
  • 2,485
  • 6
  • 13