Search code examples
javakotlinreactive-programmingspring-webfluxproject-reactor

How to update a Webflux object from repository and save it back


I want to 1) get an object from my repository, 2) update that object and then 3) save it back.

I've already done first two things:

fun updateUniversity(id: ObjectId,
                     newName: String,
                     newCity: String,
                     newYearOfFoundation: Int): Mono<University> {
    return universityRepository
        .findById(id)
        .switchIfEmpty(Mono.error(NoSuchElementException()))
        .map {
            if (newCity.isNotEmpty()) it.city = newCity
            if (newName.isNotEmpty()) it.name = newName
            if (newYearOfFoundation != -1) it.yearOfFoundation = newYearOfFoundation
            return@map it
        }
}

But I can't save the result. If I try to save my object through map .map{ universityRepository.save(it) } I get an error Type Mismatch, cause it returns Mono in Mono.

.then{ universityRepository.save(it) } also is not my case, because I need to pass a value (which I don't have) in save function.

I can call .block() but it smells too.

So could anyone show what the last line should be to save my updated object back in the repository?


Solution

  • The problem was that to save an object we need to use .flatMap not just .map. Because .map just transforms elements and .flatMap converts them to new Publishers. https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html