Coroutines Basics
1. What are coroutines in Kotlin?
Coroutines are a concurrency design pattern that allows you to write asynchronous code more easily and efficiently.
2. How do you launch a coroutine in Kotlin?
Kotlin
Copied
3. What is the difference between launch
and async
in coroutines?
launch
is used for fire-and-forget tasks, while async
is used for tasks that return a result.
4. Explain the purpose of suspend
functions in coroutines.
suspend
functions can be called from coroutines, and they can suspend execution without blocking the thread.
5. How do you define a suspend
function in Kotlin?
Kotlin
Copied
6. What is the purpose of the CoroutineScope
in coroutines?
CoroutineScope
is used to control the lifecycle of coroutines and provides a structured concurrency mechanism.
7. How can you use structured concurrency in coroutines?
Kotlin
Copied
8. Explain the use of async
and await
for concurrent tasks in coroutines.
Kotlin
Copied
9. What is the purpose of the withContext
function in coroutines?
withContext
is used to switch the coroutine's context while keeping the same coroutine.
10. How can you handle exceptions in coroutines?
Kotlin
Copied
11. Explain the use of runBlocking
in coroutines.
runBlocking
is used to start a coroutine from a non-suspending function, providing a convenient way to write coroutine-based code in the main
function.
12. What is the difference between launch
and runBlocking
in coroutines?
launch
is used to launch a new coroutine without blocking the current thread, while runBlocking
blocks the current thread until the coroutine inside it completes.
13. How can you cancel a coroutine in Kotlin?
Kotlin
Copied
14. What is the purpose of the CoroutineExceptionHandler
in coroutines?
CoroutineExceptionHandler
is used to handle uncaught exceptions in coroutines.
Kotlin
Copied
15. How can you use coroutines with Android development?
Android developers use coroutines to perform asynchronous operations, such as network requests or database access, without blocking the UI thread.
16. What is the purpose of yield
in coroutines?
yield
is used to suspend a coroutine and allow other coroutines to run. It's often used in scenarios where cooperative multitasking is needed.
17. How do you work with multiple coroutines concurrently in Kotlin?
Kotlin
Copied
18. Explain the concept of coroutine context and dispatchers.
Coroutine context represents the execution context of a coroutine, and dispatchers define the thread or threads on which coroutines are executed.
19. How can you ensure that coroutines are executed sequentially?
Kotlin
Copied
20. How do you use asynchronous
coroutines for parallelism in Kotlin?
Kotlin
Copied