I have code that needs to interact with two reactive dependencies - saving to a database and publishing to a stream, each of which return Mono instances. After this, I need to do some more processing - all using the original object I started with, something like this:
val myObject = Mono.just(“thing”);
myObject.flatMap(repository::save)
.flatMap(stream::publish)
.map(obj -> moreProcessing(obj));
But the problem is, repository.save doesn’t return a Mono of the object I’m interested in and neither does stream.publish.
I can achieve what I want with something like:
myObject.flatMap(obj -> repository.save(obj).then(Mono.just(obj))
.flatMap(obj -> stream.publish(obj).then(Mono.just(obj))
.map(obj -> moreProcessing(obj));
i.e. mapping to the dependency functions just to get their behaviour and then mapping straight back again, but this seems odd - like I might be missing some better way to use the API which doesn’t give the hint that I’m mapping between types, because that’s not what I’m using flatMap for, really.
I can also go with something like:
myObject.flatMap(obj ->
repository.save(obj)
.flatMap(x -> publisher.stream(obj))
.map(x -> moreProcessing(obj)));
but that doesn’t seem like a great way to go either, as it’s going to lead to hard-to-maintain code in even relatively simple cases.
Thoughts?