Sure! Let's look at a few simple examples to understand how Kotlin coroutines work in practice. I'll start with the basics and move on to slightly more complex examples.
1. Launching a Simple Coroutine
In this example, we launch a coroutine that prints a message after waiting for 1 second. This demonstrates how to use the launch
coroutine builder and the delay
function.
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine in the background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is milliseconds)
println("World!") // print after delay
}
println("Hello,") // main coroutine continues while a previous one is delayed
}
2. Waiting for a Coroutine to Finish
Here, we use the async
builder to start a coroutine that returns a result. We then use await
to wait for the result without blocking. This example shows how to perform tasks asynchronously and wait for their completion.
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferredResult = async { // starts a new coroutine that can compute a result
delay(2000L) // simulate a long-running computation
"I've computed this result"
}
println("Waiting for the result...")
println(deferredResult.await()) // wait for and retrieve the result
}
3. Running Code in a Specific Thread Context
This example demonstrates how to switch contexts using withContext
. It's useful when you need to perform an operation on a different thread, like updating the UI in a desktop or Android app.
import kotlinx.coroutines.*
fun main() = runBlocking {
withContext(Dispatchers.IO) { // switch to the IO dispatcher for performing blocking IO operations
// Simulate a blocking IO operation
delay(1000L)
println("IO operation completed on thread: ${Thread.currentThread().name}")
}
}
4. Combining Coroutines with Suspend Functions
Suspend functions can be called from coroutines or other suspend functions. They are useful for performing asynchronous, non-blocking operations.
import kotlinx.coroutines.*
suspend fun performTask(): String {
delay(1000L) // pretend to do some work asynchronously
return "Task Completed"
}
fun main() = runBlocking {
launch {
val result = performTask()
println(result)
}
}
These examples illustrate the basics of creating and managing coroutines in Kotlin, including launching coroutines, waiting for results, switching contexts, and using suspend functions for asynchronous operations. As you dive deeper into Kotlin coroutines, you'll discover more advanced features and patterns for handling complex asynchronous programming tasks.