Coroutines Flashcards
Define the relationship between Coroutines and Dispatchers (3)
- All Coroutines must run in a Dispatcher
- Dispatchers determine which threads are used for Coroutine execution
- Coroutines can suspend themselves, and the dispatcher is responsible for resuming them
What are the four types of CoroutineDispatchers and their purposes?
Default - optimised to perform CPU-intensive work outside of the main thread
IO - offloads blocking IO tasks to a shared pool of threads
Main - confined to the Main thread operating with UI objects.
Unconfined - mandates no specific threading policy - executes coroutine immediately on the current thread and later resumes it in whatever thread called resume
What is the purpose of a runBlocking block?
- Bridges synchronous and asynchronous functions.
- Blocks thread calling the async function until it returns.
- Specifically for use in main functions and tests
What are the steps for executing work on a non-main thread?
- Define a CoroutineScope
val myScope = CoroutineScope(Dispatchers.Default) - Launch CoroutineScope
myScope.launch{ }
When within a CoroutineScope, how do you come back to do work on the main thread?
withContext(Dispatchers.Main){ }
Why do we launch coroutines within a scope?
Any coroutine launched in a scope is automatically cancelled if the scope’s owner is cleared. (e.g. Navigating away from a ViewModel’s fragment)
What advantages do Coroutines have over Callbacks?
Coroutines are written sequentially so they are easier to read and maintain.
Coroutines can safely use valuable language features such as exceptions (callbacks cannot).
What is the difference between blocking and suspending?
If a thread is blocked, no other work happens.
If the thread is suspended, other work happens until the result is available.
What 3 things are needed to use coroutines in Kotlin?
Job: anything that can be canceled. Every coroutine has a job, and you can use the job to cancel the coroutine.
Dispatcher: The dispatcher sends off coroutines to run on various threads.
Scope: A coroutine’s scope defines the context in which the coroutine runs. A scope combines information about a coroutine’s job and dispatchers.
eg ViewModelScope / LifecycleScope / liveData