How to perform Flatten with reactor?

Asked

Viewed 25 times

0

I have a list of strings, where I convert to a Flux. And, for each Flux, I perform a flatMap which, in turn, returns a list. Further ahead I run a collectList() which converts Flux to a list. As a result within the map I have a List<List<String>>, but what I really want is a List. However, I could not accomplish the flatten of this guy, and having only one List<String> with all values within.

fun getAllValues() {
    var values: List<String> = listOf("value 1", "value 2")

    values
        .toFlux()
        .flatMap { findMoreValues() }
        .collectList()
        .map { /* Aqui possuo um List<List<String>> */ }
}


fun findMoreValues(): List<String> {
    callExternalApi() // retorna por exemplo listOf("value 3", "value 4")
}

1 answer

0

You can turn a List<String> in a Flux<String> with:

flatMap + fromIterable:

values
    .toFlux()
    .flatMap { Flux.fromIterable(findMoreValues()) }
    .collectList()
    .map { /* List<String> */ }

flatMap + toFlux

values
    .toFlux()
    .flatMap { findMoreValues().toFlux() }
    .collectList()
    .map { /* List<String> */ }

flatMapIterable:

values
    .toFlux()
    .flatMapIterable { findMoreValues() }
    .collectList()
    .map { /* List<String> */ }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.