okfm
okfm

Reputation: 3

Is it a good pattern to subscribe a Mono before return it?

I want to subscribe a Mono before return it, the consumer of the subscriber will do some work like write some info, the code looks like this:

    Mono result = a remote call by WebClient;
    result.subscribe(data->successLog(log,JSON.toJSONString(data)));
    return result;

and now the problem comes:

that remote call by WebClient will triggered twice!

how to subscribe a Mono and do something before return it?

Upvotes: 0

Views: 1743

Answers (1)

bsideup
bsideup

Reputation: 3063

It is not :)

In Reactive Streams, everything is "lazy" by default: you're not "calling operations" (imperative), you're building a pipeline that will later be executed (where subscribe() is what triggers the execution).

If you need to log when Mono successfully resolves, you can use Mono#doOnNext:

return result.doOnNext(data -> successLog(log, JSON.toJSONString(data)));

This way it will log every time your Mono is resolved.
Why "every time"? Because, in Reactive Streams, it is absolutely valid to re-subscribe on the same Mono (e.g. for retrying).

Upvotes: 2

Related Questions