How expensive are coroutines? :thinking_face: I me...
# announcements
a
How expensive are coroutines? 🤔 I mean, what might go wrong if I do something like this?
d
Wrong? As long as the second function is cancellable it should be fine.
âś… 1
f
Well, depending on second function, third may not be called
a
Second function is a cancellable coroutine-buttonListener adapter (created using
suspendCancellableCoroutine
) just like the
Animator.awaitEnd()
in here https://medium.com/androiddevelopers/suspending-over-views-19de9ebd7020
trap is, views can be destroyed anytime while we want our coroutine to be viewmodel-scoped.
giving the trap 🔝 , the “wait for button click” is a bad idea. But what about waiting for something else that is not tied to view-lifecycle ? 🤔
or, waiting for view-lifecycle-tied events but in a
viewLifecycleOwner.lifecycleScope
(e.g. waiting for animation to end).
e
When the view is killed off, all the coroutines inside are cancelled as well, even if they are on other dispatchers. The only danger would be launching something in a separate scope (i.e. a different Job hierarchy), but in that case that scope should be governed by the lifecycle of something else. Note that when a coroutine is suspended it is literally not running. It’s off in a queue on a dispatcher somewhere waiting to be resumed. The only memory it takes up is the memory required for any local variables within the suspend function.
a
The only memory it takes up is the memory required for any local variables within the suspend function
so having tens of coroutines (with reasonable local variables) waiting to be resumed is no overhead. 👌
e
Pretty much! For more info I highly recommend checking this video out which explains what coroutines look like when they’re compiled:

https://youtu.be/YrrUCSi72E8â–ľ

a
Great, thanks!