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