Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
188: WorkManager for Background Tasks
You've probably reached a point in your project where you have a task that just has to happen, regardless of whether the user keeps the app open. Maybe it's syncing a local database of bookmarked recipes to your cloud server, or uploading a heavy telemetry log. Your first instinct—especially if you've been leaning heavily on coroutines—is to just launch a job in a scope and call it a day. I've seen this a hundred times in code reviews, and while it looks clean, it's a ticking time bomb.
The "Just Launch a Coroutine" Trap
The naive approach is to trigger your background work from a ViewModel or a Service using something like viewModelScope.launch. It feels right because it's asynchronous and doesn't block the UI. For a quick API call to refresh a feed, this is perfect. But imagine you're uploading a 10MB image file. You start the coroutine, the upload begins, and then the user swipes the app away from the Recents menu or the OS decides it needs more RAM for a foreground game and kills your process.
// The fragile way
fun uploadProfilePicture(imageUri: Uri) {
viewModelScope.launch {
try {
repository.uploadImage(imageUri)
_uiState.value = Success
} catch (e: Exception) {
_uiState.value = Error(e)
}
}
}
In this scenario, the moment the process is killed, your coroutine is annihilated. The upload stops mid-stream. The user thinks it's working, but the server is just left with a corrupted partial file. You might try to fix this with a Foreground Service, but that's overkill if the task doesn't need to be immediate and requires a persistent notification that might annoy the user.
Where the Process Dies
The fundamental trade-off here is between concurrency and persistence. Coroutines are for concurrency; they manage how code runs while the process is alive. WorkManager is for persistence. When you schedule a task with WorkManager, it doesn't just start a thread—it writes the task details into an internal SQLite database. This means if the phone reboots or the app crashes, WorkManager looks at its database upon restart and says, "Oh, I still have this upload pending," and kicks it off again.
Moving to Guaranteed Execution
To do this the right way, you pull the logic out of the ViewModel and into a Worker. This is where you define the actual work. I like to think of the Worker as a standalone unit of execution that doesn't care who started it or if the UI is even currently visible.
class UploadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val imageUri = inputData.getString("IMAGE_URI") ?: return Result.failure()
return try {
repository.uploadImage(imageUri)
Result.success()
} catch (e: Exception) {
// This tells WorkManager to try again later with exponential backoff
Result.retry()
}
}
}
The real magic, however, isn't just that it survives process death—it's the constraints. You can tell Android, "Only run this if the user is on Wi-Fi and the device is charging." Doing this manually with coroutines would require you to write a nightmare of BroadcastReceivers and connectivity listeners. With WorkManager, it's just a configuration object.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.build()
val uploadRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.setConstraints(constraints)
.setInputData(workDataOf("IMAGE_URI" to uriString))
.build()
WorkManager.getInstance(context).enqueue(uploadRequest)
Now, you've shifted the responsibility from the volatile memory of a ViewModel to the OS itself. You're no longer praying that the user doesn't close the app; you're instructing the system to handle the execution based on the environment.
📋 Practical Task
Build a Reliable Log Uploader with Network Constraints
You are tasked with creating a "Log Uploader" feature. The app collects system logs locally, and these logs need to be sent to a server. Because logs can be large, they should only be uploaded when the device is connected to an unmetered network (Wi-Fi) and the battery is not low.
Requirements:
- Create a
LogUploadWorkerthat extendsCoroutineWorker. - Inside
doWork(), simulate a network call usingdelay(2000). Randomly returnResult.retry()20% of the time to test WorkManager's rescheduling logic andResult.success()otherwise. - In your Activity or ViewModel, create a
OneTimeWorkRequestfor this worker. - Apply
Constraintsto ensure the work only runs onNetworkType.UNMETEREDand requires that the battery is not low (setRequiresBatteryNotLow(true)). - Enqueue the work using
WorkManager.getInstance(context).enqueue().
There are no comments for now.