Kotlin Coroutines

📌Coroutine Scopes

A coroutine should run in a scope. The scope is used in order to track the lifecycle of the coroutine. Also it is a way to bind the coroutine(s) to an app specific lifecycle.

  • Keep track of the running coroutine
  • Cancel work when it is not longer necessary to run it
  • Notify errors when something bad happens to a coroutine

⛏️Coroutine Builders

Coroutine Builders are extension functions of CoroutineScope used to build and manage the execution of the coroutine.

🔖run()

Function definition

  • lambda with a receiver
  • return type is whatever the lambda returns
  • there is also a non-extension version of this function

🔖runBlocking

Function definition

  • Runs a new coroutine
  • Blocks current thread interruptible until its completion
  • Could set a name to the coroutine for debug purposes
runBlocking(CoroutineName("pink-coroutine"))

🔖launch()

Function definition

  • Extension function of CoroutineScope
  • Launches a new coroutine
  • Does not block the current thread
  • Returns a reference to the coroutine as a Job

🔖suspend functions

Function definition

  • Suspend the execution of the current task and let another task execute
  • Could be called only from within a coroutine
  • There are 2 functions that could help us to achieve this behavior:
  • delay() => pause the currently executing task for a specific time (milliseconds)
  • yield() => let other task to be executed

🔖async / await

Function definition

  • async() is an extension function of CoroutineScope
  • If we want to execute a task asynchronously and get the result, then we should use async() instead of launch() function.
  • async() creates a new coroutine and returns its future result as an implementation of Deferred<T> which has an await() function very helpful in order to get the status of the coroutine.
  • The call to await() will wait for the coroutine started by async() to complete.

⛓️Coroutine Context and Threads

CoroutineContext defines the context in which the coroutine will run.

Specific Context

When we want to run our tasks on a dedicated thread pool the solution is to use the proper dispatchers from the Dispatchers classes.

  • Dispatchers.Default — Different thread (if possible). It is backed by a shared pool of threads on JVM => CPU
  • Dispatchers.Main — Platform specific main thread (if exists) => UI/Non-blocking
  • Dispatchers.IO — Thread designed for offloading blocking IO tasks to a shared pool of threads => Network and disk
  • Dispatchers.Unconfined — Always uses the first available thread (most performant dispatcher).

Custom pool of threads

When we want to run our tasks by using our own custom thread pool we apply the asCoroutineDispatcher function on Java’s ExecutorService.

  • Executors.newSingleThreadExecutor()
  • Executors.newFixedThreadPool()
  • Executors.newScheduledThreadPool()
  • Exectors.newCachedThreadPool()

Change the CoroutineContext

If we want to run a coroutine in one context and then change the context midway the solution is to use the withContext() function.

❌Cancelling coroutines

Coroutines can be cancelled. A coroutine is cancelled only if it is currently in a suspension point.

🔖cancel()

  • Cancels the Job

🔖join()

  • Suspends the coroutine until the current job is complete

🔖cancelAndJoin()

  • Cancels the job and suspends the invoking coroutine until the cancelled job is complete.

🔖withTimeout()

  • Helpful to use it when a job might be taking too long
  • The function runs a suspending block of code inside a coroutine and throws a TimeoutCancellationException if the timeout is exceeded

🔖withTimeoutOrNull

  • Runs a given suspending block of code inside a coroutine with a specified timeout and returns null if this timeout was exceeded.

✨The magic behind the scenes…

Under the hood when we use coroutines we actually work with Continuation objects. This class contains the results of the partial execution of the function so that the result can be sent to the caller by using the Continuation callback.

📚Learn more…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Magda Miu

Magda Miu

Engineering Manager @Adobe | Android @GoogleDevExpert | Blogger, Speaker, Trainer #android #kotlin #gde #agile #leadership