Reputation: 22008
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 String
s, but can't wrap my head around
List
Map
Upvotes: 0
Views: 1089
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
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