Last active
June 9, 2019 09:10
-
-
Save malvinstn/9ae1321a38f0d4b6f38c765368cfb143 to your computer and use it in GitHub Desktop.
Kotlin merge 2 different Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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