0
votes

I have a WebApplication written in Kotlin. It is a chat kinda like Discord. I have a function which does several things. The function itself is used to delete the account of the user but while doing this, it is also deleting the messages which he have ever written off the database, he gets removed of all the groups in the database and in the groups where he was the admin a new admin is chosen.

And this function does look like this:

fun deleteAccount(userId: String) : Flux<Void>{
        return groupRepository.findAllByAdmin(userId)
                .flatMap{
                    if(it.users.size<1) groupRepository.deleteById(it._id)
                    it.admin = it.users[0]
                    it.users.remove(userId)
                    groupRepository.save(it)
                }
                .flatMap {
                    messageRepository.deleteMessageByUserId(userId)
                    userRepository.deleteById(userId)
                }

    } 

My repositories look like this:

@Repository
interface GroupRepository : ReactiveCrudRepository<GroupRequest, String> {

    fun findByName(name: String): Mono<GroupRequest>
    fun existsByName(name: String): Mono<Boolean>
    fun findAllByAdmin(admin:String) : Flux<GroupRequest>

}

@Repository
interface MessageRepository : ReactiveCrudRepository<Message, String> {

    fun findMessageByGroupId(groupId: String): Flux<Message>
    fun deleteMessageByUserId(userId:String) : Mono<Void>
}

So the last 2 statements in my function return a void Mono. The problem is it does not matter which statement is executed first, only one of the 2 statements is executed and I tried several things now including Flux.zip it does not work completely. If I put the deleteMessages first, everything works except the part where the user is deleted of the database. Where is the problem in this function and how can I fix it?

2

2 Answers

0
votes

I fixed it by zipping both statements in the second flatMap, looks like this:

fun deleteAccount(userId: String) : Flux<Void>{
        return groupRepository.findAllByAdmin(userId)
                .flatMap{
                    if(it.users.size<1) groupRepository.deleteById(it._id)
                    it.admin = it.users[0]
                    it.users.remove(userId)
                    groupRepository.save(it)
                }
                .flatMap {
                    Mono.zip(messageRepository.deleteMessageByUserId(userId),userRepository.deleteById(userId)).map {
                        it.t1
                    }
                }

    }
0
votes

You might be looking for Mono.when() if all you care about is the completion signal.