Androider2
Androider2

Reputation: 507

How to combine results from a suspend function and a flow in kotlin?

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 ->
  ...
}

Upvotes: 3

Views: 1548

Answers (1)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17500

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) }

Upvotes: 5

Related Questions