Reputation: 5904
I've been trying to wrap my head around coroutines and I believe I have a fairly good understanding now, but there's still a couple things that aren't clear which I have questions about.
Imagine I have the below code:
lateinit var item: Int
val coroutine = globalScope.launch {
item = onePlusOne()
}
suspend fun onePlusOne(): Int {
return 1+1
}
When the suspend function onePlusOne
is called, it doesn't start a new coroutine correct? It is still executing in the same one started by launch?
When the suspend function onePlusOne
is called, it doesn't automatically suspend the coroutine that launch created right? If it does, how does it still execute the return 1+1
statement?
Upvotes: 0
Views: 79
Reputation: 8106
- When the suspend function onePlusOne is called, it doesn't start a new coroutine correct? It is still executing in the same one started by launch?
Yes, a coroutine is only created when you create one from CoroutineScope.launch or CoroutineScope.async, withContext or runBlocking.
A suspend function does not create a new coroutine, but can suspend the caller if it calls any suspend function from inside it (it can be change of thread/dispatcher using withContext and waiting for the result, it can be a delay, or you are using suspendCancellableCoroutine to wrap a callback and resume/return the value as function return, and many more).
When the suspend function onePlusOne is called, it doesn't automatically suspend the coroutine that launch created right? If it does, how does it still execute the return 1+1 statement?
Yes it doesn't suspend it, unless you call a suspend function it is not suspended.
Suspend functions aren't magical that they suspend on their own, they are same as a non-suspend function, but they have one extra parameter appended at the time of compilation accepting a Continuation, which basically work as a callback to pause (suspend) and resume a coroutine.
Upvotes: 3