K.Nicholas
K.Nicholas

Reputation: 11551

Is more Reactive better?

Given a method I can write reactive code in two ways:

public String getString() { return "Hello, World"; }

or

public Mono<String> getMonoString() { return Mono.just("Hello, World"); }

And then use it with either

someOtherPublisher.map( value-> getString() + value ).subscribe(System.out::println);

or

someOtherPublisher.flatMap( value-> getMonoString().map(str-> str + value ) ).subscribe(System.out::println);

My question is whether more reactive is better? I was arguing that the extra overhead of getMonoString was worse because of overhead and performance and the other was arguing that having methods be publishers and using .flatMap was better because it was "more reactive".

I am interested in finding some authority on why one is better or worse than the other or even whether it matters.

Clearly I could do some simple tests but sometimes simple tests can fail to be convincing.

Upvotes: 0

Views: 219

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14712

first of all.

public String getString() { return "Hello, World"; }

this is not reactive. This is a standard imperative function, that has 0(1) time complexity. So over n number of runs this will perform sort of the same.

This is reactive:

public Mono<String> getMonoString() { return Mono.just("Hello, World"); }

But this also has 0(1) time complexity. Which means, that there is a possibility that it will switch threads in the middle of it, but the chance is very unlikely. Over n number of runs this will also perform sort of the same.

None of your examples matter, because non of them actually take any time.

When reactive shines is when dealing with side effects. Things that take time, like database calls, http calls, File I/O etc. etc.

Reactive is good when threads need to wait.

Upvotes: 3

Related Questions