The suspend modifier

One specific goal of the Kotlin team was to make as few language changes as possible in order to support concurrency. Instead, the impact of supporting coroutines and concurrency was to be taken by the compiler, the standard library, and the coroutines library. So the only relevant change from a language perspective is the addition of the suspend modifier.

This modifier indicates to the compiler that the code in the given scope—function or lambda—will work using continuations. So whenever a suspending computation is compiled, its bytecode will be a big continuation. For example, let's consider this suspending function:

suspend fun getUserSummary(id: Int): UserSummary {
logger.log("fetching summary of $id")
val profile = fetchProfile(id) // suspending fun
val age = calculateAge(profile.dateOfBirth)
val terms = validateTerms(profile.country, age) // suspending fun
return UserSummary(profile, age, terms)
}

What we are telling the compiler here is that the execution of getUserSummary() will happen through a Continuation. So the compiler will use a Continuation to control the execution of getUserSummary(). In this case, the function suspends twice: first when fetchProfile() is invoked, and later for the execution of validateTerms(). You can always count on IntelliJ IDEA and Android Studio to show you the suspension points of a function:

The arrows on the left represent a call to a suspending function, so they represent suspension points.

That means that our function's execution will happen in three steps. First, the function will be started and the log will be printed, then the invocation of fetchProfile() will cause the execution to suspend; once fetchProfile() has ended, our function will calculate the age of the user, and then the execution will suspend again for validateTerms() to be executed. The last step will occur once the terms are validated, when the function resumes one last time, and all the data from the previous steps is used to create the summary of the user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.28.108