How do you define a coroutine in Kotlin?
In Kotlin, coroutines are defined using the suspend keyword, which marks a function as capable of being suspended and resumed asynchronously. Suspended functions can contain suspension points where the coroutine can be paused and later resumed without blocking the thread.
Here’s a basic example demonstrating the definition of a coroutine in Kotlin:
kotlin import kotlinx.coroutines.* suspend fun myCoroutine() { delay(1000) // Simulate a suspension point println("Coroutine executed!") }
In this example, myCoroutine() is a suspended function that simulates a delay of 1000 milliseconds using delay() from the kotlinx.coroutines package. The suspend keyword indicates that the function can be suspended and resumed asynchronously.
To launch and execute the coroutine, you typically use coroutine builders such as launch, async, or runBlocking, which provide different concurrency primitives and execution models.