-
Notifications
You must be signed in to change notification settings - Fork 23
What is suspending function and how it works
Devrath edited this page Jan 22, 2024
·
6 revisions
-
Suspending functions
offer a promise that the function will not be blocking the calling thread(main-thread) -
Suspending functions
might be or might not be blocking - So remember just calling a suspend function does not mean that it's always long-running. -
Suspend functions
can only be called from another suspend function or a coroutine-builder
- It is also a suspending function that suspends the execution for the time duration passed into it.
- We understand that coroutines rely on the concept of
suspending code
andsuspending functions
. -
Suspending Code
-> This unlike the regular code, the system can pause its execution and continue it later on. - System differentiates between
suspend function
andregular function
based on thesuspend keyword
. - Calling a regular function from a to
suspend function
is that unlike theregular function
, thesuspend function
had to be wrapped in alaunch block
because that is how the coroutines API are built. - Unlike the threads where we call
thread.sleep()
to delay the execution, in the coroutines we calldelay()
.
-
Continuation
forms the foundation of coroutines, and it is the most important part where suspend functions differ from regular ones. - The system uses it to
continuation
to navigate around the call stack and code in general. - They use it to navigate
from
andto
betweencall point
andwhere to
it is called. - Consider we call
delay()
in a suspend function on a line inside the suspend function, this creates acontinuation object
determining a flow of execution. - There can be multiple execution points in a
suspend function
. - Code usually wraps the function that is called from
suspending
function with the continuation arguments and so because once the execution of the called function is finished, the called function checks the label of the continuation object and returns to the point of execution from where it is called. - Before the label called function can serve the purpose, if an exception happens, the exception is thrown
- Every time a function is called in a program, It is added to the call stack, This is the stack of all the functions in the order that they were called and held in memory and haven't finished execution yet.
- Continuation is like a callback but implemented at a very low system level.
- It controls how and when the program will execute and what the result is going to be, whether it's an exception or a value.
- When one function finishes it takes it off the stack and proceeded with the next function.
- The important point here to note is knowing where to return.
- Continuation holds the information like
context in which the function was called
,variables & parameters passed for the function
.