Language Elements

Data Types

Kotlin Classes

Kotlin Operators

Kotlin Constructors

Kotlin Null Safety

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Kotlin Collections

Kotlin Data Structures

Kotlin Algorithms

Delegation

Lateinit and Lazy Initialization

Kotlin Scope Functions

Kotlin Key Words

Kotlin Example Codes

Kotlin Interview Questions

Coroutines in Kotlin provide a lightweight and powerful solution for asynchronous and concurrent programming. While platforms like Android have traditionally used tools like AsyncTask (now deprecated), ThreadPoolExecutor, or RxJava, Kotlin coroutines offer a modern alternative built into the language. They avoid callback hell, use less memory (lightweight) and CPU resources (smart scheduling), reduce memory leaks, and are easier to manage.

Coroutines allow concurrent code execution without blocking threads. They are not threads themselves, but rather lightweight code blocks that are executed on threads and can suspend and resume without blocking those threads. This enables thousands of coroutines to run efficiently on a limited number of threads — making them ideal for server applications, Android apps, desktop tools, and more.

Main Coroutine Features

Kotlin's suspend Function

A suspend function is a special Kotlin function that can be paused and resumed. It is declared using the suspend keyword and can only be called from another suspend function or within a coroutine.

Suspending a function does not block the thread; it simply pauses the coroutine's execution until the result is ready, freeing the thread to do other work.

Note: In Android, calling a suspend function directly inside onCreate() or other lifecycle methods is not allowed. You must launch a coroutine first.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Launch coroutine
        GlobalScope.launch {
            // Call suspend function here or from another suspend function
        }
    }
}
        

Quiz Questions


Copyright © by Zafar Yasin. All rights reserved.