fweigl
fweigl

Reputation: 22008

Create observable for each item in list and combine their results

I have the following two Single functions:

fun getStrings(): Single<List<String>> {
    return Single.just(listOf("a", "a.b", "a.b.c"))
}

fun getStringParts(s: String): Single<List<String>> {
    return Single.just(s.split("."))
}

I want to combine them in a way that results in a Map<String, List<String> where the key is the result of the first function and the value is the result of the second function for each String, so

["a":["a"], "a.b":["a", "b"], "a.b.c":["a", "b", "c"]]

I use the first function, receive a List of Strings, but can't wrap my head around

Upvotes: 0

Views: 1089

Answers (2)

Gustav Karlsson
Gustav Karlsson

Reputation: 1221

val result = getStrings()
    .flattenAsObservable { it }         // Turn the list into a stream of items
    .flatMapSingle { key ->             // Take each item
        getStringParts(key)             // Get its parts
            .map { value ->
                key to value            // Combine key and value
            }
    }                                   // You now have a stream of pairs
    .toMap({ it.first }, { it.second }) // Build the map
    .blockingGet()

println(result)                         // {a=[a], a.b=[a, b], a.b.c=[a, b, c]}

Upvotes: 3

michalbrz
michalbrz

Reputation: 3494

getStrings()
       .flattenAsFlowable { it }
       .flatMapSingle { s -> getStringParts(s).map { parts -> s to parts } }
       .toMap({ it.first }, { it.second })

This returns type Single<MutableMap<String, List<String>>>.

I hope everything is clear but if you have some doubts feel free to ask.

Upvotes: 3

Related Questions