3

Guys imagine I have these two sources of data:

val flowA: Flow<String>
suspend fun funB(): Int

How can I combine the result of both into a flow (let's say Flow<Pair<String, Int>>)?

How about the approach below? Is there a better way?

combine(
  flowA,
  flow {emit(funB())}
) { a, b ->
  ...
}
1
  • 1
    You want to put that same Int with all the strings in flow? Commented Nov 17, 2021 at 16:14

1 Answer 1

5

Assuming you want the same Int paired with each String in flowA, you can do it as follows:

val funBResult = funB()
val pairs = flowA.map { it to funBResult }

If funB() is in fact a function that takes the String as a parameter, you could do something like:

val pairs = flowA.map { it to funB(it) }
1
  • The problem with this is that the second line will not start before the first completes resulting in unnecessary delays, especially if the source of data is linked to a network call. Isn't the approach suggested by the question itself better? Commented Aug 9, 2023 at 15:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.