Reputation: 3706
So I want to create a Mono<Void>
(or any Mono<SomeIgnorableType>
) that actually emits an element.
Why? Because I actually want to run an effect, and the result just implies the effect was run, YET, it can be ignored.
In Haskell Void is an uninhabitable type... like the Nothing
in Scala. In Java Void is also uninhabitable, yet it is used more like the Unit
type in Scala or the ()
(0 arity tuple) in Haskell. A type with only one inhabitant.
Ok, too much with the theory. My options so far:
Mono.just((Void) null)
throws an Exception.
Mono.empty().single()
(because I actually want to emit an event), ends up with failure, when one subscribes to it. And...
Mono.just("something").then()
runs the effect, but then I cannot chain it with other monos, because it only emits complete and error events.
So how???
Upvotes: 8
Views: 11574
Reputation: 72284
Java's lack of null-safety means the unit type concept doesn't translate particularly well. I've never been convinced when people have postulated Void
as equivalent to a unit type. You can never instantiate it by design; you can assume that any reference containing the Void
type is null
, which I don't really see as a value - it's more the absence of any value (ie. an uninhabitable type.)
There's nothing that I would consider a "real" unit type built into Java, but you can create one trivially via the use of an enum
with a single value:
public enum Unit {UNIT}
If your Mono
type is then set to Unit
, this does what you need - you can either complete the Mono
with no value, you can complete it with a single Unit
value (and ignore the value, just reacting to the fact it's there), or complete it with an error. It sounds like that's exactly what you're after.
That said, answering the question directly and ignoring whether you should (you shouldn't IMHO), you can mock Void
to actually assign it a non-null value. Mockito can do it no problem, you just need to make sure Mockito is configured so it can mock final classes:
Void v = Mockito.mock(Void.class);
Mono.just(v)
.doOnNext(actualVoid -> System.out.println(actualVoid))
.block();
Prints: Mock for Void, hashCode: 1830745997
(It's not something I've ever done, nor felt the need to do, but that doesn't prevent you from technically doing it.)
Upvotes: 4