Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

251
Views
What is suspendCoroutine?

I am a beginner studying coroutines.

Not exactly, but I have a little understanding of what a coroutine is.

The suspend function is also difficult, but with a little understanding.

I'm studying step by step, but there are parts I don't understand.

That's suspendCoroutine. In the sample code, suspendCoroutine and Continuation used in the block appear, but I have no idea what these two are.

I've looked on other sites, but I can't find anywhere that explains it easily.

Can you explain what suspendCoroutine and Continuation are used for easily and, if possible, with an example?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

suspendCoroutine is a builder function that mainly used to convert callbacks into suspend functions. Let's say for example you have some legacy (or not) Api, that uses callbacks. You can easily transform it into a suspend function to call it in a coroutine. For example:

suspend fun getUser(id: String): User  = suspendCoroutine { continuation ->
      Api.getUser(id) { user ->
          continuation.resume(user)
      }
}

Here we have an Api function getUser, which defined in Api class for example like this:

fun getUser(id: String, callback: (User) -> Unit) {...}

suspendCoroutine suspends coroutine in which it executed until we decide to continue by calling appropriate methods - Continuation.resume.... suspendCoroutine mainly used when we have some legacy code with callbacks.

Using suspendCoroutine to convert callbacks into suspend functions makes the code sequential when you work with suspend functions.

For example instead of having a callback hell like this:

Api.getUser(id) { user ->
      Api.getProfile(user) { profile ->
          Api.downloadImage(profile.imageId) { image ->
              // ...
          }
      } 
}

after you apply suspendCoroutine to those callbacks and convert them into suspend functions, the code will look like the following:

val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!