coroutine cycle and what does suspend do?

Hi everyone,

since weeks I’m trying to understand the coroutines to a certain degree. I know the basics, why they exist, when to use, the advantages but I’m struggling with the whole lifecycle and what the “suspend” keyword really does.

The reason why I’m asking here is that I’ve read tons of articles, official documentation and so on, but sometimes it didn’t fully answer my question or has lead to even more confusion as one articles says A and the next says B.

So let us make a simple example:

  • we have a suspend-function networkRequest()
  • we run that from the main-thread on an android-UI

So, somewhere there is a launch{} and within that launch you’re calling the suspend function

launch{} does build a new coroutine (let’s say A) and that one calls the networkRequest() (say B). Correct?

the suspend-keyword on B does suspend coroutine A and that’s why the main-thread can work on “other” things or even other coroutines. Is that correct?

Once B has done it’s work, it returns and A is being continued. Does B wake up A or is the scope doing that job?

Say there was a context-switch “withContext(Dispatchers.IO)” before we called “networkRequest()”, would that also have released the coroutine A from the main-thread?

Thanks for giving me assistance here. Cheers!

submitted by /u/therealmcz
[link] [comments]