Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

combine(
  flowA,
  flow {emit(funB())}
) { a, b ->
  ...
}

>Solution :

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) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading