How to Create Coroutine in Kotlin: Simple Guide
In Kotlin, you create a
coroutine by launching it inside a CoroutineScope using builders like launch or async. You need to use kotlinx.coroutines library and call runBlocking or other scopes to start coroutines.Syntax
To create a coroutine, use a coroutine builder like launch or async inside a CoroutineScope. The runBlocking function can start a coroutine in a blocking way for simple examples.
- runBlocking: Starts a coroutine and blocks the current thread until it finishes.
- launch: Starts a new coroutine without blocking the current thread.
- async: Starts a coroutine that returns a result with
Deferred.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { launch { // Coroutine code here println("Hello from coroutine!") } }
Output
Hello from coroutine!
Example
This example shows how to create and run a coroutine using launch inside runBlocking. The coroutine prints a message after a delay, demonstrating asynchronous behavior.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(500L) // Pause coroutine for 500 milliseconds println("Coroutine says hello after delay") } println("Main thread continues") }
Output
Main thread continues
Coroutine says hello after delay
Common Pitfalls
Common mistakes when creating coroutines include:
- Not using a
CoroutineScopeto launch coroutines, which can cause them to not run or leak. - Forgetting to add
kotlinx-coroutines-coredependency. - Using
Thread.sleep()instead ofdelay()inside coroutines, which blocks the thread. - Not handling coroutine cancellation properly.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { // Wrong: Using Thread.sleep inside coroutine blocks the thread launch { Thread.sleep(500L) // Blocks the thread, bad practice println("This blocks the thread") } // Right: Use delay to suspend coroutine without blocking launch { delay(500L) println("This does not block the thread") } }
Output
This blocks the thread
This does not block the thread
Quick Reference
Here is a quick summary of coroutine builders and their use:
| Builder | Description |
|---|---|
| runBlocking | Starts a coroutine and blocks current thread until it completes (good for main functions and tests). |
| launch | Starts a new coroutine without blocking, returns a Job to manage it. |
| async | Starts a coroutine that returns a Deferred result, useful for concurrent computations. |
| delay | Suspends coroutine without blocking thread for given time. |
Key Takeaways
Use coroutine builders like launch or async inside a CoroutineScope to create coroutines.
runBlocking is useful to start coroutines in main functions or tests by blocking the thread.
Always use delay instead of Thread.sleep to avoid blocking threads inside coroutines.
Add kotlinx-coroutines-core dependency to use Kotlin coroutines.
Manage coroutine lifecycle properly to avoid leaks and unexpected behavior.