Hi all, I’ve got multi-platform Kotlin code which ...
# coroutines
t
Hi all, I’ve got multi-platform Kotlin code which uses coroutines, and it is important that things really execute in parallel. For my specific use case there is no real problem except for when targeting JavaScript, as that’s single-threaded and a coroutine has to actually be suspended in order for other things to execute. The solution I’m currently using is to call
delay(1)
in several places, to achieve just that: when any coroutine hits the
delay(1)
its execution is suspended, allowing others to run (and complete or hitting
delay(1)
themselves, allowing suspended coroutines to resume). And it generally seems to work. But it’s not elegant, and the delay itself, while not that noticeable, is not necessary. Is there another way to do it? Something I can do at certain places in the code to allow a coroutine to suspend execution just in order to allow others to run until they complete or do the same?
c
maybe
yield()
?
t
Interesting. First of all, thanks! I wasn’t aware of this
yield()
, which seems to be what I was looking for. Secondly, there seems to be some subtle difference in functionality in practice: I’ve noticed that when I was using
delay(1)
garbage collection would sometimes take place before the coroutine resumed, and with
yield()
it doesn’t seem to happen. Does someone know why that is, and advise on how to enable garbage collection to take place (it’s not normally a concern, I know, but for one of my use cases this is actually important)?