Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine two publisher in one in spring reactor

I have implemented a dummy reactive repository but I am struggling with the update method:

@Override
public Mono<User> updateUser(int id, Mono<User> updateMono) {
    return  //todo with getUser
}

@Override
public Mono<User> getUser(int id) {
    return Mono.justOrEmpty(this.users.get(id));
}

From one hand I have incoming publisher Mono<User> updateMono, from the other hand I have another publisher during Mono.justOrEmpty(this.users.get(id)).

How to combine it together, make update, and give back just one publisher?

The only thing come to my mind is:

@Override
public Mono<User> updateUser(int id, Mono<User> updateMono) {
    return  getUser(id).doOnNext(user -> {
        updateMono.subscribe(update -> {
            users.put(id, new User(id, update.getName(), update.getAge()));
            System.out.format("Updated user with id %d to %s%n", id, update);
        });
    });
}

Is it correct?

like image 567
Sergii Getman Avatar asked Jan 03 '23 14:01

Sergii Getman


1 Answers

See the reference guide on finding the right operator

Notably, for Mono you have and, when, then (note this last one will become flatMap in 3.1.0, and flatmap will become flatMapMany)

doOnNext is more for side operations like logging or stats gathering. Subscribe inside subscribe is another bad form; generally you want flatMap or similar instead.

like image 88
Simon Baslé Avatar answered Apr 01 '23 21:04

Simon Baslé