When is the deal Mono.fromCallback ? (reactive)

Viewed 110

I still do not understand when to apply this method. In fact, it is similar to Mono.just, but I heard that callback is used for heavy operations if it needs to be performed separately from other flows. Now I use it like this, but is it correct.

Here is an example of use, I wrap sending a firebase notification in a callback since the operation is long

 @Override
    public Mono<NotificationDto> sendMessageAllDevice(NotificationDto notification) {
        return Mono.fromCallable(() -> fcmProvider.sendPublicMessage(notification))
                .thenReturn(notification);
    }

maybe I still had to wrap up here in Mono.just ?

3 Answers

It depends which thread you want fcmProvider.sendPublicMessage(...) to be run on.

Either the one currently executing sendMessageAllDevice(...):

T result = fcmProvider.sendPublicMessage(notification);
return Mono.just(result);

Or the one(s) the underlying mono relies on:

Callable<T> callable = () -> fcmProvider.sendPublicMessage(notification);
return Mono.fromCallable(callable);

I would guess you need the latter approach.

If you use Mono.just(computeX()), computeX() is called immediately. No want you want(I guess).

If you use Mono.fromCallable(() -> computeX()), the computation is still not performed. I mean computeX() is only called when you subscribe to it. Maybe using .map, .flatMap, etc.

Important: if computeX() return Mono you doe not need to use Mono.fromCallable. It's only for blocking code

As you explained in the description, Mono.fromCallable is used when you want to compute a result with an async execution (mostly some heavy operation).

Since, you have already generated the Mono with Mono.fromCallable you do not have to wrap it again with Mono.just.

Related