Last active
September 30, 2022 12:01
-
-
Save houssemzaier/603ce09b198dfded7fcd08b42ea5f764 to your computer and use it in GitHub Desktop.
onEach and flowOn
This file contains hidden or 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
package fr.x | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.flow | |
import kotlinx.coroutines.flow.flowOn | |
import kotlinx.coroutines.flow.onEach | |
import kotlinx.coroutines.runBlocking | |
import org.junit.Test | |
/** | |
* Unit tests of [MaasPaymentMethodsViewModel]. | |
*/ | |
class MaasPaymentMethodsViewModelTest { | |
@Test | |
fun main() { | |
println( | |
""" | |
*Start: running in : ${Thread.currentThread()} | |
""".trimIndent(), | |
) | |
runBlocking { | |
flow { | |
for (i in 1..5) { | |
emit(i) | |
delay(200) | |
println( | |
""" | |
*emitting: running in : ${Thread.currentThread()} | |
""".trimIndent(), | |
) | |
} | |
} | |
.onEach { | |
delay(100) | |
println( | |
""" | |
*delaying: running in : ${Thread.currentThread()} | |
""".trimIndent(), | |
) | |
} | |
.flowOn(Dispatchers.IO) | |
.collect { println(it) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
changing the code to this:
will give this output:
*Start: running in : Thread[Test worker,5,main]
*delaying: running in : Thread[Test worker @coroutine#1,5,main]
1
*emitting: running in : Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main]
*delaying: running in : Thread[Test worker @coroutine#1,5,main]
2
*emitting: running in : Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main]
*delaying: running in : Thread[Test worker @coroutine#1,5,main]
3
*emitting: running in : Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main]
*delaying: running in : Thread[Test worker @coroutine#1,5,main]
4
*emitting: running in : Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main]
*delaying: running in : Thread[Test worker @coroutine#1,5,main]
5
*emitting: running in : Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main]