Return value when Flux completes?
Asked Answered
G

2

5

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?

Glycol answered 22/1, 2019 at 12:56 Comment(0)
D
7

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));
Decrypt answered 22/1, 2019 at 13:17 Comment(0)
E
4

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");
Euphroe answered 23/1, 2019 at 12:50 Comment(1)
thenReturn is only on Mono, not FluxLemkul

© 2022 - 2024 — McMap. All rights reserved.