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 . Coroutines are basically of two types: Stackless Stackful Stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t map on the native thread. Kotlin Coroutines Features. Lightweight- One can run many coroutines on a single thread due to support for suspension, which doesn’t block the thread where the coroutine is running. Suspending frees memory over blocking while supporting multiple concurrent operations. Built-in cancellation support : Cancellation is generated automatically through the running coroutine hierarchy. Fewer memory leaks : It uses structured concurrency to run operations within a scope. Jetpack integration : Many Jetpack libraries include extensions that provide full corou...
Suspending Functions Suspending functions are a cornerstone of Kotlin Coroutines. They are the functions that can be paused and resumed at a later time. To define a suspending function, you use the suspend modifier. Here's a simple example: import kotlinx.coroutines.* suspend fun doSomething () { delay( 1000L ) println( "Doing something" ) } fun main () = runBlocking { launch { doSomething() } } In this code, doSomething is a suspending function. Inside doSomething , we're delaying for one second and then printing a message. We're calling doSomething from a coroutine, because suspending functions can only be called from another suspending function or a coroutine.