Sobes.tech
Junior — Middle

Can you name the key classes used when working with Coroutines?

sobes.tech AI

Answer from AI

Key classes and interfaces when working with Kotlin Coroutines in Android:

  • CoroutineScope — defines the scope in which coroutines are launched and manages their lifecycle.
  • Job — represents a coroutine task, allows cancellation and tracking of its state.
  • Deferred<T> — an extension of Job that returns a result of type T (used with async).
  • Dispatchers — defines the thread or thread pool on which the coroutine runs (e.g., Dispatchers.Main, Dispatchers.IO).
  • CoroutineContext — the context of a coroutine, combining Job, Dispatcher, and other elements.
  • launch — function to start a coroutine without a return value.
  • async — function to start a coroutine with a return value (Deferred).

Example of launching a coroutine:

CoroutineScope(Dispatchers.Main).launch {
    val data = withContext(Dispatchers.IO) {
        // Long operation, e.g., network request
        fetchData()
    }
    updateUI(data)
}