Hi everyone, I wonder if someone could clarify som...
# coroutines
c
Hi everyone, I wonder if someone could clarify something for me. When I first learned about coroutines, I remember being taught that one should prefer to use
launch
from your existing context and then move it elsewhere using
withContext
instead of calling
launch
and specifying dispatcher.
scope.launch { withContext(<http://Dispatchers.IO|Dispatchers.IO>) { work() } }
instead of
scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { work() }
. I remember this being described as preferential since there was some performance penalty when launching in a different context that did not occur when moving a running coroutine using
withContext
. I’m trying to find guidance on this again and I can’t find anything about it. Did I misunderstand something when I was first learning?
z
I’ve never heard that ever, and it doesn’t make any sense to me. Just pass the context to launch.
c
Yeah, it does seem strange. I just wish I could figure out where I got this idea. It’s definitely not something I would have made up, I must have misunderstood something really early on. 🤔
f
you are probably thinking of
Default
and
IO
which share a common thread pool and switching between those may not do an actual thread switch
u
What you remember might be more like a convention. It goes like this. A suspend function should never block the calling thread. This results in two invariants: a) you never need to switch context before calling a suspend function. b) a suspend function that blocks (e.g. for blocking io) needs to switch context before doing so. So in most cases you just launch and leave the context switching to the suspend functions you call
👌 1
💯 1
c
@uli This sounds right! I did more reading last night and found recommendations like this. I must have conflated the reasoning for it in my head a while back and didn’t question it until now. This does make sense. Thank you all for weighing in!