Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Suspend Function In Kotlin Coroutines
Next article icon

Suspend Function In Kotlin Coroutines

Last Updated : 10 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Kotlin Coroutines on Android

The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code.

The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.

Suspend Function In Kotlin

Suspend function is a function that could be started, paused, and resume. One of the most important points to remember about the suspend functions is that they are only allowed to be called from a coroutine or another suspend function. An example is given below, in which we have tried to call the delay() function from outside of the coroutine.

Kotlin
// sample kotlin program to show use of delay function class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)                  // will throw a error         delay(1000L)                  GlobalScope.launch{          // delay function (a suspend function) must called within coroutine          // or another suspend function         }      } } 

As we have called the delay function from outside of the coroutine, it will throw the error as below:

On hovering over the delay function we can see the error.

Delay Function

It is represented as delay(), It is a suspend function which delays coroutine for a given time without blocking a thread, and resumes it after a specified time. When we add the suspend keyword in the function, all the cooperations are automatically done for us. We don't have to use when or switch cases in order to switch from one function to another. Let's take an example of suspend function as:

Kotlin
// arbitrary do task function for explanation suspend fun dotask(request: Request): Response {   // perform the task } 

Though it seems that only one argument has passed to dotask() function, but internally there are two arguments. Internally, it gets converted by the compiler to another function without the suspend keyword with an extra parameter of the type Continuation<T> like below:

Kotlin
// internal conversion of suspend function dotask() fun dotask(request: Request, continuation: Continuation)... 

The way suspend functions communicate with each other is with Continuation objects. A Continuation is just a generic callback interface with some extra information, which looks like below(taken from Kotlin source code):

Kotlin
// Continuation interface structure public interface Continuation<in T> {   public val context: CoroutineContext   public fun resumeWith(result: Result<T>) } 
  • context will be the CoroutineContext to be used in that continuation.
  • resumeWith resumes execution of the coroutine with a Result, that can contain either a value which is the result of the computation that caused the suspension or an exception.

Note: From Kotlin 1.3 onwards, you can also use the extension functions resume(value: T) and resumeWithException(exception: Throwable) which are specialized versions of the resumeWith call.

The two extension functions of resumeWith are given by:

  1. fun <T> Continuation<T>.resume(value: T)
  2. fun <T> Continuation<T>.resumeWithException(exception: Throwable)

We can see the two extension function that they can be used to resume the coroutines with a return value or with an exception if an error had occurred while the function was suspended. This way, a function could be started, paused, and resume with the help of Continuation. We just have to use the suspend keyword.

Kotlin
// Kotlin Program to demonstrate use of suspend function class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)                    GlobalScope.launch{           val networkCallAnswer==doNetworkCall()           Log.d("Main-Activity,networkCallAnswer)         }      }          suspend fun doNetworkCall():String {     delay(2000L);     return "Network Call Answer"     }                } 

We get the Log output after a delay of 2 seconds, since we have called doNetworkCall() from a coroutine, we have to make doNetworkCall() function as suspend.


Next Article
Suspend Function In Kotlin Coroutines

L

lavishgarg26
Improve
Article Tags :
  • Kotlin
  • Android

Similar Reads

    Scopes in Kotlin Coroutines
    Scope in Kotlin's coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. Kotlin CoroutinesScope is a term well used in the referred for the interface used for defining the Scope(lifetime and context
    6 min read
    Exception Handling in Kotlin Coroutines
    Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
    7 min read
    Kotlin - Scope Function
    There are several functions in the Kotlin standard library that help in the execution of a block of code within the context of an object. Calling these functions on an object with lambda expression creates a temporary scope. These functions are called Scope Functions. We can access the object of the
    7 min read
    withContext in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on AndroidLaunch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is
    3 min read
    Dispatchers in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on Android It is known that coroutines are always started in a specific context, and that context describes in which threads the coroutine will be started in. In general, we can start the coroutine using GlobalScope without passing any parameters to it, this is done w
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences