Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

335
Views
Combine two kotlin flows into a single flow that emits the latest value from the two original flows?

If we have two flows defined like this:

val someflow = flow {
    emit("something")
}

and another flow defined like:

val stateFlow = MutableStateFlow("some value")

Is it possible to combine the two flows into a single flow that just emits the last value emitted by either someflow or stateFlow?

The idea is that stateFlow might emit a value at some point in the future, but until that happens I just want whatever value someflow last emitted. In the "combined" flow, I would like to just take the first value emitted by someflow but then be able to observe the rest of the updates on stateFlow.

It seems like this might be accomplished with a combine function, but I just want to emit the latest emitted value between the two flows, I don't care about what the last value of one flow was.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

There is a flattenMerge function, which executes flows as a single flow, it might be what you need. For example:

val numbersFlow = flowOf("1", "2", "3", "4").onEach { delay(1000) }
val lettersFlow = flowOf("A", "B", "C").onEach { delay(2000) }
flowOf(numbersFlow, lettersFlow).flattenMerge().collect {
    println("Result $it")
}

Prints:

Result 1
Result A
Result 2
Result 3
Result B
Result 4
Result C

So for your case it would look something like:

flowOf(someFlow, stateFlow).flattenMerge().collect {
    println("Result $it")
}
over 4 years ago · Santiago Trujillo Report

0

You can use something like this:

fun <T> Flow<T>.merge(otherFlow: Flow<T>) = flow {
    this@merge.collect { value ->
        emit(value)
    }
    otherFlow.collect { value ->
        emit(value)
    }
}

Note that the resulting flow will only finish when both flows are completed/canceled.

Usage:

someFlow.merge(stateFlow).collect {
    println(it)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!