Now, does this mean that while the coroutine is suspended that the suspend function is still doing work?
No, it means that other functions can do work while it is suspended.
This is what confuses me because I've seen many texts say that it pauses not only the coroutine but also the suspend function.
This is correct.
But if it pauses the suspend function as well then whats the point if the work you wanted to be done is paused?
The main use case is delegating work to external resources, especially the networking layer. While your function is awaiting the data to come in from the network, it has nothing else to do. In the meantime other coroutines may go on executing on the same thread.
Suppose I had a suspend function that takes 30 seconds to finish doing some mathematical calculation.
That function, even though declared suspendable, probably wouldn't actually suspend itself. It would keep occupying the calling thread.
And then I had another coroutine that said printed some simple text like "Hello, World".
If you're on a single-threaded dispatcher, that coroutine would have to wait its turn until the first coroutine explicitly suspends itself, which would probably not happen inside the CPU-intensive function you mention.
If the first coroutine suspends and goes to the second coroutine to print the greeting, would mathematical calculation still be happening at the same time?
No, a suspended coroutine doesn't do any work.
For example, the first coroutine may call yield()
within its computation loop and thus allow Kotlin to suspend it and run some other coroutines on the same thread. It wouldn't make any progress while suspended.
You can see it like this: let's say there is a single thread running all coroutines. The manner in which they will run is called cooperative concurrency. A coroutine must explicitly suspend itself to allow others to run. This is very similar to several threads running concurrently on a single CPU core, except that the OS can do one more "magical" thing: it can suspend the thread at any time, without that thread's permission. Which is why this kind is called pre-emptive concurrency.