Android WorkManager Input/Output — Complete Guide
In this tutorial, you'll learn about Android WorkManager Input/Output. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your worker ignores the input parameters, or you try to pass a complex object and it silently fails because Data only supports primitives.
Wrong Approach ❌
// Trying to pass a complex object directly
val input = workDataOf("user" to User("Alice", 30)) // Won't compile
val request = OneTimeWorkRequestBuilder<ProcessWorker>()
.setInputData(input)
.build()
// Worker that ignores input
class ProcessWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
// Uses hardcoded values instead of inputData
val url = "https://example.com/default"
return Result.success()
}
}
Output: Compilation error for complex objects. Worker processes wrong data.
Right Approach ✅
// Pass data as primitives or serialized strings
val input = workDataOf(
"user_id" to "alice123",
"file_url" to "https://example.com/data.json",
"retry_count" to 3,
"is_priority" to true
)
val request = OneTimeWorkRequestBuilder<DownloadWorker>()
.setInputData(input)
.build()
class DownloadWorker(context: Context, params: WorkerParameters) :
Worker(context, params) {
override fun doWork(): Result {
val userId = inputData.getString("user_id") ?: return Result.failure()
val fileUrl = inputData.getString("file_url") ?: return Result.failure()
val retryCount = inputData.getInt("retry_count", 0)
// Download logic...
val output = workDataOf("downloaded_path" to "/tmp/$userId.json")
return Result.success(output)
}
}
Output: Worker reads correct input and produces typed output.
Prevention
- Only pass primitives (
String,Int,Long,Boolean,Float,Double) inData. - Use
workDataOf()for building input/output — it's type-safe. - Total
Datasize limit is 10KB per worker. - Serialize complex objects to JSON strings within the limit.
Common Mistakes with workmanager input
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro