Hi all! I am learning Flow, and was trying to unde...
# coroutines
d
Hi all! I am learning Flow, and was trying to understand how a flow can consume other flows in parallel and what happens in error scenarios. Here’s a test that I can’t get to work (requirements are documented in the
handler
function): https://pl.kotl.in/zyHCNXVLg
I have been using custom jobs and scopes, but unable to apply in flow.
flowOn
does not seem to work either.
e
I think you’re looking for `merge()`: https://pl.kotl.in/XQGDN3Kww
d
Thanks @Evan R.! While merge helps parallelize the db() and nw() calls, it still doesn’t help in 2 areas: 1. running the 2 tasks using separate threads/dispatchers (printed logs will show this info) 2. if an exception happens in one, second is not auto-cancelled (please replace db() with dbError() to test this)
e
Dispatchers.Default and Dispatchers.IO share the same thread pool. The only difference is that if there are not enough threads available in the Dispatchers.Default pool, Dispatchers.IO will spawn new threads
Also try this updated version to test the auto-cancellation: https://pl.kotl.in/MvhuASBGr In your original example, nw() would complete before dbError() threw the exception. If you update nw() to emit another value after dbError() throws the exception you will see that it doesn’t emit the final message or complete.
👍 1
d
This makes sense. Thank you!
i think the dispatcher code is confusing - i am not actually using them, simply because i didn’t know how to.
let’s say i want to run the db() and nw() calls using separate scope with custom dispatchers using https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.util.concurrent.-executor/as-coroutine-dispatcher.html , how can i achieve that?
e
You can see some examples here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt For example, you can create a JVM threadpool and then conver that into a coroutine executor using .asCoroutineDispatcher() Coroutine dispatchers just handle scheduling of coroutines on threads
d
I am facing issues running a flow using a dispatcher that was created using Executor.asCoroutineDispatcher(). how to specify the dispatcher used for flow execution? flowOn() throws errors.