Coroutines Flashcards

1
Q

Define the relationship between Coroutines and Dispatchers (3)

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the four types of CoroutineDispatchers and their purposes?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of a runBlocking block?

A
  • Bridges synchronous and asynchronous functions.
  • Blocks thread calling the async function until it returns.
  • Specifically for use in main functions and tests
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the steps for executing work on a non-main thread?

A
  1. Define a CoroutineScope
    val myScope = CoroutineScope(Dispatchers.Default)
  2. Launch CoroutineScope
    myScope.launch{ }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When within a CoroutineScope, how do you come back to do work on the main thread?

A

withContext(Dispatchers.Main){ }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why do we launch coroutines within a scope?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What advantages do Coroutines have over Callbacks?

A

Coroutines are written sequentially so they are easier to read and maintain.

Coroutines can safely use valuable language features such as exceptions (callbacks cannot).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the difference between blocking and suspending?

A

If a thread is blocked, no other work happens.

If the thread is suspended, other work happens until the result is available.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What 3 things are needed to use coroutines in Kotlin?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly