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.
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
Jobobject (used to cancel the coroutine or check its status). - Analogy: Sending an email; once you hit send, you move on to other tasks.
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).
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.
| Builder | Return Type | Use Case | Thread Impact |
|---|---|---|---|
launch | Job | Background tasks with no result. | Non-blocking |
async | Deferred<T> | Tasks that return a value. | Non-blocking |
runBlocking | T | Testing or bridging code. | Blocking |
Comments
Post a Comment