Coroutines
Overview
Provided by Kotlin to support and simplify the manage of asynchronous operation.
Coroutines are asynchronous but not necessarily multi threaded.
Coroutines vs Threads
Coroutine
Threads
Lightweight threads
Expensive
Managed by user
Managed by OS
No context switching on processors
Threads are blocking
Threads
Coroutines
Coroutines Builder
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
launchlaunchsimply returns aJobobjectFire and forget type, can't return data
async
asyncasyncreturns aDeferredobject (likepromiseandfuturein other language)Perform task and return result
runBlocking
runBlockingrunBlockingis 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
Suspend Function
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.
Dispatcher
Coroutine context / builder provide a Coroutine dispatcher.
A Dispatcher determines which thread the coroutine is run on.
Last updated
Was this helpful?