-
Couldn't load subscription status.
- Fork 24
What is suspending function and how it works
Devrath edited this page Jan 22, 2024
·
6 revisions
-
Suspending functionsoffer a promise that the function will not be blocking the calling thread(main-thread) -
Suspending functionsmight be or might not be blocking - So remember just calling a suspend function does not mean that it's always long-running. -
Suspend functionscan 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 codeandsuspending functions. -
Suspending Code-> This unlike the regular code, the system can pause its execution and continue it later on. - System differentiates between
suspend functionandregular functionbased on thesuspend keyword. - Calling a regular function from a to
suspend functionis that unlike theregular function, thesuspend functionhad to be wrapped in alaunch blockbecause 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().
-
Continuationforms the foundation of coroutines, and it is the most important part where suspend functions differ from regular ones. - The system uses it to
continuationto navigate around the call stack and code in general. - They use it to navigate
fromandtobetweencall pointandwhere toit is called. - Consider we call
delay()in a suspend function on a line inside the suspend function, this creates acontinuation objectdetermining a flow of execution. - There can be multiple execution points in a
suspend function. - Code usually wraps the function that is called from
suspendingfunction 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.
