What are Coroutine Builders?

 In Kotlin, coroutine builders are the primary way to create and start a coroutine. They act as the entry point from regular functions into the world of suspension.

1. launch

The launch builder is used for "fire and forget" tasks. It starts a coroutine that performs work in the background without returning a specific result to the caller.

  • Returns: A Job object (used to cancel the coroutine or check its status).
  • Analogy: Sending an email; once you hit send, you move on to other tasks.

2. async

The async builder is used when you need to calculate a result asynchronously. It allows for parallel execution of tasks.

  • Returns: A Deferred<T>, which is a non-blocking future.
  • Result: You must call .await() to get the actual value once it is ready.
  • Analogy: Ordering a pizza; you get a receipt (the Deferred) and eventually use it to get your pizza (the result).

3. runBlocking

This builder is a bridge between regular blocking code and the coroutine world. It blocks the current thread until the code inside finishes.

  • Returns: The result of the code block.
  • Usage: It should generally only be used in main() functions or unit tests. Never use it in production UI code as it will freeze the application.
  • Analogy: A "stop" sign; everything waits until the task is complete.

Summary Table

BuilderReturn TypeUse CaseThread Impact
launchJobBackground tasks with no result.Non-blocking
asyncDeferred<T>Tasks that return a value.Non-blocking
runBlockingTTesting or bridging code.Blocking


Comments

Popular posts from this blog

What is a Coroutine? Why is it better than threads?

Sealed Classes and Sealed Interfaces