Skip to content
This repository has been archived by the owner on Aug 16, 2023. It is now read-only.

Unclear wording/explanation for how 'suspend' does not block main thread. #157

Open
dissident76 opened this issue Dec 18, 2021 · 0 comments

Comments

@dissident76
Copy link

As a coroutines complete beginner I struggled for a couple of hours trying to understand how 'suspending' does not block main thread.

If I understood well how it all workds (please let me know if I'm wrong), I found this sentence could be misleading for beginners (Section 5, but also in the Medium articles):

A coroutine started on Dispatchers.Main won't block the main thread while suspended.

That was initially making me think that 'suspend' by itself would provide main-safety, when we are actually assuming that at some point there will be a context switch inside one of the 'suspend' functions in the lower layers (DB, network, JSON parsing, etc).

I think this key point should be more developed for beginners (green box in Section 5, 'Coroutines offer main-safety')

However, blocking code like sorting a list or reading from a file still requires explicit code to create main-safety, even when using coroutines. This is also true if you're using a networking or database library that doesn't (yet) support coroutines.

It should be better emphasised that is not the magic of 'suspend' that keeps the coroutine from blocking the main thread, but good coding practices that mandate that somewhere down the line one suspend function, usually the one that does the heavy work in the lower layers, will switch threads with either withContext(Dispatcher.Default or .IO or any other background dispatcher) or suspendCancellableCoroutine(), which is what I understood that libraries like Room and Retrofit do, or suspend functions like delay().

I'd change that sentence to something like:

A coroutine started on Dispatchers.Main SHOULD NOT block the main thread while suspended

and maybe briefly repeat how a low-level suspend function or a library can be made main-safe by switching context.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant