2
votes

I'd like to return a value (or publisher) after a Flux is completed. Here's an example with (pseudo) code that resembles what I'm after:

val myId : Mono<String> = fetchMyId()
myId.flatMap { id ->
     someFlux.map { .. }.doOnNext { ... }.returnOnComplete(Mono.just(id))
}

I.e. I want to return id after someFlux has completed. The returnOnComplete function is made-up and doesn't exists (there's a doOnComplete function but it's for side-effects) which is why I'm asking this question. How can I do this?

2

2 Answers

6
votes

You can use the then(Mono<V>) operator, as it does exactly what you want according to the documentation:

Let this Flux complete then play signals from a provided Mono.

In other words ignore element from this Flux and transform its completion signal into the emission and completion signal of a provided Mono<V>. Error signal is replayed in the resulting Mono<V>.

For example:

Mono
    .just("abc")
    .flatMap(id -> Flux.range(1, 10)
        .doOnNext(nr -> logger.info("Number: {}", nr))
        .then(Mono.just(id)))
    .subscribe(id -> logger.info("ID: {}", id));
5
votes

On top of then(Mono<V>), as suggested by @g00glen00b, there is a thenReturn(V) method that is a bit shorter to write/clearer when your continuation is a simple Mono.just:

mono.then(Mono.just("foo")); //is the same as:
mono.thenReturn("foo");