Android Development Android Background Processing 2 — Questions and Answers
Question 1: What is the purpose of CoroutineScope in Kotlin?
- To define the lifecycle and context in which coroutines run (Correct answer)
- To limit CPU usage of coroutines
- To scope database transactions
- To define UI boundaries
Correct answer: To define the lifecycle and context in which coroutines run
CoroutineScope defines a scope for launching coroutines, ensuring they are cancelled when the scope is cancelled (e.g., when a ViewModel is cleared).
Question 2: Which WorkManager class is used to chain multiple work tasks sequentially?
- WorkContinuation (Correct answer)
- WorkChain
- SequentialWork
- WorkPipeline
Correct answer: WorkContinuation
WorkContinuation allows you to create chains of WorkRequests that execute sequentially or in parallel using then() and combine() methods.
Question 3: What does the suspend keyword do to a Kotlin function?
- Marks it as a suspending function that can be paused and resumed (Correct answer)
- Pauses the function permanently
- Makes it run on a background thread
- Delays its execution
Correct answer: Marks it as a suspending function that can be paused and resumed
The suspend keyword marks a function as a coroutine that can suspend its execution without blocking the calling thread.
Question 4: Which Android component replaced IntentService for background processing?
- WorkManager
- JobIntentService
- CoroutineService
- Both A and B (Correct answer)
Correct answer: Both A and B
Both WorkManager and JobIntentService replaced IntentService, with WorkManager being preferred for most deferrable background work.
Question 5: What is the viewModelScope in Android?
- A CoroutineScope tied to the ViewModel's lifecycle that cancels when the ViewModel is cleared (Correct answer)
- A scope for observing LiveData in ViewModels
- A scope limiting database access to ViewModels
- A UI scope for composables
Correct answer: A CoroutineScope tied to the ViewModel's lifecycle that cancels when the ViewModel is cleared
viewModelScope is an extension property on ViewModel that provides a CoroutineScope automatically cancelled when the ViewModel is destroyed.
Question 6: How do you specify Constraints for a WorkManager WorkRequest?
- Using the Constraints.Builder class (Correct answer)
- Using @Constraint annotation
- Using WorkManager.setConstraints()
- Using ConstraintSet
Correct answer: Using the Constraints.Builder class
Constraints.Builder is used to build a Constraints object specifying network type, charging state, storage, and other requirements for work execution.
What is the purpose of CoroutineScope in Kotlin?