Skip to content

Instantly share code, notes, and snippets.

@malvinstn
Last active June 9, 2019 09:10
Show Gist options
  • Save malvinstn/9ae1321a38f0d4b6f38c765368cfb143 to your computer and use it in GitHub Desktop.
Save malvinstn/9ae1321a38f0d4b6f38c765368cfb143 to your computer and use it in GitHub Desktop.
Kotlin merge 2 different Flow
fun <T> Flow<T>.mergeWith(other: Flow<T>): Flow<T> = flow {
coroutineScope {
launch {
collect { emit(it) }
}
launch {
other.collect { emit(it) }
}
}
}
@FlowPreview
fun intFlow(): Flow<Int> = flow {
for (i in 0..5) {
emit(i)
delay(100)
}
}
@FlowPreview
fun stringFlow(): Flow<String> = flow {
for (s in arrayOf("a", "b", "c")) {
emit(s)
delay(50)
}
}
@FlowPreview
suspend fun main() {
try {
intFlow()
.map { "$it" }
.mergeWith(stringFlow())
.flowOn(Dispatchers.IO)
.collect { result ->
println(result)
}
} catch (e: Exception) {
println("Flow exception: $e")
}
}
/**
* Prints:
* a
* 0
* b
* 1
* c
* 2
* 3
* 4
* 5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment