Coroutines
Last updated
Was this helpful?
Last updated
Was this helpful?
Provided by Kotlin to support and simplify the manage of asynchronous operation.
Coroutines are asynchronous but not necessarily multi threaded.
Coroutine
Threads
Lightweight threads
Expensive
Managed by user
Managed by OS
No context switching on processors
Threads are blocking
Threads
Coroutines
Coroutine have to be 'managed'. To manage a coroutine, it has to be launched inside a context which we called builder.
The job of coroutine builder is launches a new coroutine concurrently with the rest of code.
launch
launch
simply returns a Job
object
Fire and forget type, can't return data
async
async
returns a Deferred
object (like promise
and future
in other language)
Perform task and return result
runBlocking
runBlocking
is a coroutine builder that runs a coroutine code, but blocks the main thread until the coroutine itself is finished.
runBlocking can return a type
Common place to use runBlocking is when you're writing test
A function with suspend modifier executes the code without blocking the thread where its running.
Only allowed to be called from coroutine blocks or other suspend function.
Coroutine context / builder provide a Coroutine dispatcher.
A Dispatcher determines which thread the coroutine is run on.