Sobes.tech
Middle

What are the main classes in Kotlin Coroutines?

sobes.tech AI

Answer from AI

The main classes and concepts in Kotlin Coroutines:

  • CoroutineScope: Defines the lifecycle of coroutines launched within it. Allows cancelling all child coroutines.

  • Job: Represents a handle to a coroutine. Allows tracking its state, waiting for completion, or cancelling.

  • Deferred: A special type of Job that represents a value that will be available later. Used for async computations, with the result obtained via .await().

  • Dispatcher: Determines the thread or thread pool where the coroutine runs. Main dispatchers:

    • Dispatchers.Default: For CPU-intensive tasks.
    • Dispatchers.IO: For blocking I/O operations.
    • Dispatchers.Main: Main thread, for UI updates.
    • Dispatchers.Unconfined: Starts in current thread, resumes in any thread that resumes the suspending function.
  • Suspending functions: Functions marked with suspend that can be paused and resumed later. They can call other suspending functions.

  • runBlocking: Blocks the current thread until all coroutines inside complete. Used mainly for testing and main functions.

  • launch: Starts a new coroutine without blocking the current thread, returns a Job.

  • async: Starts a new coroutine without blocking, returns a Deferred.

Example usage:

// Using CoroutineScope, launch, and Dispatchers.IO
import kotlinx.coroutines.*

fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.IO)
    val job: Job = scope.launch {
        delay(1000) // simulate work
        println("Coroutine finished in ${Thread.currentThread().name}")
    }
    job.join()
    println("Main function finished")
}
// Using async and Deferred
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferredSum: Deferred<Int> = async {
        delay(500)
        1 + 1
    }
    val result = deferredSum.await()
    println("Result is: $result")
}