Search code examples
vert.xmutiny

using transformToUni


being relatively new to mutiny I am having a little difucauly wrapping my head around the following: given the following working code:

public Uni<Long> getCounterValue() {
        return  this.vertx.sharedData().getCounter(COUNTER_NAME).onItem().transformToUni(counter->counter.get());
    }

I simply want to return a Uni where the Long is a current state of a vert.x shared counter.

what is hard for me is that counter.get() actually already returns a Uni so I feel like I am doing a transformToUni on something that already has the return time I need.

I hope I explained myself. like I said, the code works but its hard for me to get the why... maybe there's also another way, more self explanatory, to achieve this?

(BTW, I looked at the guides but still I am confused)

your comments are appreciated. thanks


Solution

  • I think the explanation is that you need a new Uni that's aware of the event emitted by getCounter and that will call counter.get(). Or, in general, a new Uni that knows what to do with the result of the previous one and makes sure that everything happens in the right order at subscription.

    Let's take a simpler example, we have three Uni:

    Uni<?> first = Uni.createFrom,().item(1).invoke(System.out::print);
    Uni<?> second = Uni.createFrom().item(2).invoke(System.out::print);
    Uni<?> third = first.chain(() -> second);
    
    • If you subscribe first, it will print 1.
    • If you subscribe second, it will print 2.
    • If you subscribe third, it will print 12.

    These are three different Uni, emitting different events at different times.

    What you are suggesting is to return second when transformToUni (or chain) is called to create third. But, in that case, the result would be different from what we want.