kmpworkmanager
Production-ready Kotlin Multiplatform library for scheduling and managing background tasks on Android and iOS with a unified API. Built for enterprise applications requiring reliability, stability, and comprehensive monitoring.
Overview
KMP WorkManager provides a single, consistent API for background task scheduling across Android and iOS platforms. It abstracts away platform-specific implementations (WorkManager on Android, BGTaskScheduler on iOS) and lets you write your background task logic once in shared Kotlin code.
Enterprise Features:
- Real-time progress tracking for long-running operations
- Chain state restoration for reliability on iOS
- Comprehensive test coverage for critical components
- File-based storage for improved iOS performance
- Production-grade error handling and logging
The Problem
When building multiplatform apps, you typically need to maintain separate background task implementations:
// Android - WorkManager API
val workRequest = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(...)
.build()
WorkManager.getInstance(context).enqueue(workRequest)
// iOS - BGTaskScheduler API
let request = BGAppRefreshTaskRequest(identifier: "sync-task")
BGTaskScheduler.shared.submit(request)
This leads to duplicated logic, more maintenance, and platform-specific bugs.
The Solution
With KMP WorkManager, you write your scheduling logic once:
scheduler.enqueue(
id = "data-sync",
trigger = TaskTrigger.Periodic(intervalMs = 900_000),
workerClassName = "SyncWorker",
constraints = Constraints(requiresNetwork = true)
)
The library handles platform-specific details automatically.
Why Choose KMP WorkManager?
For Enterprise Applications
Production-Ready Reliability
- Comprehensive test coverage (200+ tests) including iOS-specific integration tests
- Chain state restoration ensures no work is lost on iOS interruptions
- Retry logic with configurable limits prevents infinite failure loops
- File-based storage with atomic operations for data integrity
Real-Time Monitoring
- Built-in progress tracking for long-running operations (downloads, uploads, data processing)
- Event bus architecture for reactive UI updates
- Step-based progress for multi-phase operations
- Human-readable status messages for user feedback
Platform Expertise
- Deep understanding of iOS background limitations (documented in detail)
- Smart fallbacks for Android exact alarm permissions
- Batch processing optimization for iOS BGTask quotas
- Platform-specific best practices and migration guides
Developer Experience
- Single API for both platforms reduces maintenance
- Type-safe input serialization
- Koin integration for dependency injection
- Extensive documentation and examples
Comparison with Alternatives
| Feature | KMP WorkManager | WorkManager (Android only) | Raw BGTaskScheduler (iOS only) |
|---|---|---|---|
| Multiplatform Support | ✅ Android + iOS | ❌ Android only | ❌ iOS only |
| Progress Tracking | ✅ Built-in | ⚠️ Manual setup | ❌ Not available |
| Chain State Restoration | ✅ Automatic | ✅ Yes | ❌ Manual implementation |
| Type-Safe Input | ✅ Yes | ⚠️ Limited | ❌ No |
| Test Coverage | ✅ Comprehensive | ✅ Yes | ❌ Manual testing |
| Enterprise Documentation | ✅ Extensive | ⚠️ Basic | ❌ Apple docs only |
Installation
Add to your build.gradle.kts:
kotlin {
sourceSets {
commonMain.dependencies {
implementation("dev.brewkits:kmpworkmanager:2.0.0")
}
}
}
Or using version catalog:
[versions]
kmpworkmanager = "2.0.0"
[libraries]
kmpworkmanager = { module = "dev.brewkits:kmpworkmanager", version.ref = "kmpworkmanager" }
Quick Start
1. Define Your Workers
Create worker classes on each platform:
Android (androidMain):
class SyncWorker : AndroidWorker {
override suspend fun doWork(input: String?): Boolean {
// Your sync logic here
return true
}
}
iOS (iosMain):
class SyncWorker : IosWorker {
override suspend fun doWork(input: String?): Boolean {
// Same sync logic - shared code!
return true
}
}
2. Create Worker Factory
Android (androidMain):
class MyWorkerFactory : AndroidWorkerFactory {
override fun createWorker(workerClassName: String): AndroidWorker? {
return when (workerClassName) {
"SyncWorker" -> SyncWorker()
else -> null
}
}
}
iOS (iosMain):
class MyWorkerFactory : IosWorkerFactory {
override fun createWorker(workerClassName: String): IosWorker? {
return when (workerClassName) {
"SyncWorker" -> SyncWorker()
else -> null
}
}
}
3. Initialize Koin
Android (Application.kt):
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApp)
modules(kmpWorkerModule(
workerFactory = MyWorkerFactory()
))
}
}
}
iOS (AppDelegate.swift):
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
KoinModuleKt.doInitKoinIos(workerFactory: MyWorkerFactory())
return true
}
4. Schedule Tasks
class MyViewModel(private val scheduler: BackgroundTaskScheduler) {
fun scheduleSync() {
scheduler.enqueue(
id = "data-sync",
trigger = TaskTrigger.Periodic(intervalMs = 900_000), // 15 minutes
workerClassName = "SyncWorker",
constraints = Constraints(requiresNetwork = true)
)
}
}
Features
Multiple Trigger Types
Periodic Tasks
scheduler.enqueue(
id = "periodic-sync",
trigger = TaskTrigger.Periodic(intervalMs = 900_000),
workerClassName = "SyncWorker"
)
One-Time Tasks
scheduler.enqueue(
id = "upload-task",
trigger = TaskTrigger.OneTime(initialDelayMs = 5000),
workerClassName = "UploadWorker"
)
Windowed Tasks (Execute within a time window)
scheduler.enqueue(
id = "maintenance",
trigger = TaskTrigger.Windowed(
earliest = System.currentTimeMillis() + 3600_000, // 1 hour from now
latest = System.currentTimeMillis() + 7200_000 // 2 hours from now
),
workerClassName = "MaintenanceWorker"
)
Note: On iOS, only
earliesttime is enforced viaearliestBeginDate. Thelatesttime is logged but not enforced by BGTaskScheduler.
Exact Alarms (Android only)
scheduler.enqueue(
id = "reminder",
trigger = TaskTrigger.Exact(atEpochMillis = System.currentTimeMillis() + 60_000),
workerClassName = "ReminderWorker"
)
Task Constraints
Control when tasks should run:
scheduler.enqueue(
id = "heavy-task",
trigger = TaskTrigger.OneTime(),
workerClassName = "ProcessingWorker",
constraints = Constraints(
requiresNetwork = true,
requiresCharging = true,
requiresUnmeteredNetwork = true, // Wi-Fi only
systemConstraints = setOf(
SystemConstraint.REQUIRE_BATTERY_NOT_LOW,
SystemConstraint.DEVICE_IDLE
)
)
)
Task Chains
Execute tasks sequentially or in parallel:
// Sequential: Download -> Process -> Upload
scheduler.beginWith(TaskRequest("DownloadWorker"))
.then(TaskRequest("ProcessWorker"))
.then(TaskRequest("UploadWorker"))
.enqueue()
// Parallel: Run multiple tasks, then finalize
scheduler.beginWith(listOf(
TaskRequest("FetchUsers"),
TaskRequest("FetchPosts"),
TaskRequest("FetchComments")
))
.then(TaskRequest("MergeDataWorker"))
.enqueue()
Type-Safe Input
Pass typed data to workers:
@Serializable
data class UploadRequest(val fileUrl: String, val fileName: String)
scheduler.enqueue(
id = "upload",
trigger = TaskTrigger.OneTime(),
workerClassName = "UploadWorker",
input = UploadRequest("https://...", "data.zip")
)
Real-Time Progress Tracking
Workers can report progress to provide real-time feedback to the UI, essential for enterprise applications with long-running operations:
In Your Worker:
class FileDownloadWorker(
private val progressListener: ProgressListener?
) : Worker {
override suspend fun doWork(input: String?): Boolean {
val totalBytes = getTotalFileSize()
var downloaded = 0L
while (downloaded < totalBytes) {
val chunk = downloadChunk()
downloaded += chunk.size
val progress = (downloaded * 100 / totalBytes).toInt()
progressListener?.onProgressUpdate(
WorkerProgress(
progress = progress,
message = "Downloaded $downloaded / $totalBytes bytes"
)
)
}
return true
}
}
In Your UI:
@Composable
fun DownloadScreen() {
val progressFlow = TaskProgressBus.events
.filterIsInstance<TaskProgressEvent>()
.filter { it.taskId == "download-task" }
val progress by progressFlow.collectAsState(initial = null)
LinearProgressIndicator(
progress = (progress?.progress?.progress ?: 0) / 100f
)
Text(text = progress?.progress?.message ?: "Waiting...")
}
Progress features:
- Percentage-based progress (0-100%)
- Optional human-readable messages
- Step-based tracking (e.g., "Step 3/5")
- Real-time updates via SharedFlow
- Works across Android and iOS
Platform-Specific Features
Android
- WorkManager integration for deferrable tasks
- AlarmManager for exact timing requirements
- Foreground service support for long-running tasks
- ContentUri triggers for media monitoring
- Automatic fallback when exact alarms permission is denied
iOS
- BGTaskScheduler integration
- Chain state restoration: Resume interrupted chains from last completed step
- Automatic re-scheduling of periodic tasks
- File-based storage for better performance and thread safety
- Thread-safe task execution with NSFileCoordinator
- Timeout protection with configurable limits
- Retry logic with max retry limits (prevents infinite loops)
- Batch processing for efficient BGTask usage
[!WARNING] Critical iOS Limitations
iOS background tasks are fundamentally different from Android:
Opportunistic Execution: The system decides when to run tasks based on device usage, battery, and other factors. Tasks may be delayed hours or never run.
Strict Time Limits:
BGAppRefreshTask: ~30 seconds maximumBGProcessingTask: ~60 seconds (requires charging + WiFi)Force-Quit Termination: All background tasks are immediately killed when user force-quits the app. This is by iOS design and cannot be worked around.
Limited Constraints: iOS does not support battery, charging, or storage constraints.
Do NOT use iOS background tasks for:
- Time-critical operations
- Long-running processes (>30s)
- Operations that must complete (use foreground mode)
See iOS Best Practices for detailed guidance.
Platform Support Matrix
| Feature | Android | iOS |
|---|---|---|
| Periodic Tasks | ✅ Supported (15 min minimum) | ✅ Supported (opportunistic) |
| One-Time Tasks | ✅ Supported | ✅ Supported |
| Windowed Tasks | ✅ Supported | ✅ Supported (earliest only) |
| Exact Timing | ✅ Supported (AlarmManager) | ❌ Not supported |
| Task Chains | ✅ Supported | ✅ Supported with state restoration |
| Progress Tracking | ✅ Supported | ✅ Supported |
| Network Constraints | ✅ Supported | ✅ Supported |
| Charging Constraints | ✅ Supported | ❌ Not supported |
| Battery Constraints | ✅ Supported | ❌ Not supported |
| ContentUri Triggers | ✅ Supported | ❌ Not supported |
Documentation
- Quick Start Guide
- Platform Setup
- API Reference
- Task Chains
- iOS Best Practices ⚠️ Read this if using iOS
- iOS Migration Guide
- Architecture Overview
Roadmap
KMP WorkManager is actively developed with a focus on reliability, developer experience, and enterprise features. Here's our planned development roadmap:
v1.2.0 - Event Persistence & Smart Retries (Q1 2026)
Event Persistence System
- Persistent storage for TaskCompletionEvents (survives app kills and force-quit)
- Automatic event replay on app launch
- Zero event loss even when UI isn't actively listening
- SQLDelight on Android, file-based storage on iOS
Smart Retry Policies
- Error-aware retry strategies (network failures vs. business logic errors)
- Exponential backoff with jitter and circuit breaker patterns
- Configurable max retry limits per task type
- Retry predicates based on error classification
Platform Capabilities API
expect object PlatformCapabilities {
val supportsExactTiming: Boolean
val supportsChargingConstraint: Boolean
val maxTaskDuration: Duration
val maxChainLength: Int
}
v1.3.0 - Typed Results & Enhanced Observability (Q2 2026)
Typed Result Data Passing
- Workers return structured results, not just Boolean
- Type-safe data flow between chained tasks
- Automatic serialization with kotlinx.serialization
sealed class WorkResult { data class Success(val data: JsonElement?) : WorkResult() data class Failure(val error: WorkError, val shouldRetry: Boolean) : WorkResult() }
Task Execution History & Analytics
- Query past task executions and their results
- Task statistics: success rate, average duration, failure patterns
- Optional SQLDelight persistence with configurable retention
- Useful for debugging and monitoring in production
Advanced Testing Support
- TestTaskScheduler for unit testing without actual execution
- Mock worker factories
- Test utilities for simulating background task scenarios
- Documentation with testing best practices
v1.4.0 - Developer Experience & Tooling (Q3 2026)
Annotation-Based Worker Discovery
@Workerannotation for automatic registration- KSP plugin for compile-time worker factory generation
- Reduces boilerplate and human error
Gradle Plugin
- Validate iOS Info.plist configuration at build time
- Detect missing BGTaskSchedulerPermittedIdentifiers
- Generate platform capability reports
Enhanced Debugging
- Built-in task monitoring UI for development builds
- Real-time visualization of scheduled, running, and completed tasks
- Export task history for analysis
Batch Operations API
scheduler.enqueueBatch(
listOf(
TaskRequest("Worker1"),
TaskRequest("Worker2"),
TaskRequest("Worker3")
)
)
v2.0.0 - Advanced Features & Platform Expansion (Q4 2026)
Desktop Support (JVM)
- Windows, macOS, Linux support
- Use native OS schedulers (Task Scheduler, launchd, systemd)
- Shared codebase with mobile platforms
Web/JS Support (Experimental)
- Service Worker integration
- Background Sync API support
- Progressive Web App (PWA) compatibility
Cloud Integration
- Optional Firebase Cloud Messaging integration for iOS background wakeup
- Remote task scheduling via push notifications
- Server-driven configuration
iOS 17+ Features
- Background Assets framework integration for large downloads
- Extended background time under optimal conditions
- Better Low Power Mode handling with adaptive intervals
Future Considerations
Features Under Research:
- Background data sync with conflict resolution
- Distributed task orchestration across devices
- ML-based optimal scheduling prediction
- Integration with Kotlin/Wasm for web workers
Contributing to the Roadmap
Have a feature request or idea? We welcome community input:
- Open a GitHub Issue with the
enhancementlabel - Join discussions on existing feature proposals
- Contribute PRs for planned features
Priority is given to:
- Features solving real developer pain points
- Cross-platform capabilities (not single-platform)
- Improvements to reliability and resilience
- Better developer experience and testing
Version History
v2.0.0 (Latest) - Package Namespace Migration
BREAKING CHANGE: Group ID changed from io.brewkits to dev.brewkits
- Maven artifact:
io.brewkits:kmpworkmanager→dev.brewkits:kmpworkmanager - Package namespace:
io.brewkits.kmpworkmanager.*→dev.brewkits.kmpworkmanager.* - Aligns with owned domain
brewkits.devfor proper Maven Central ownership
Migration Guide:
- Update dependency:
implementation("dev.brewkits:kmpworkmanager:2.0.0") - Update imports:
import dev.brewkits.kmpworkmanager.* - Clean and rebuild project
See DEPRECATED_README.md for detailed migration instructions.
v1.1.0 - Stability & Enterprise Features
- NEW: Real-time worker progress tracking with
WorkerProgressandTaskProgressBus - NEW: iOS chain state restoration - resume from last completed step after interruptions
- NEW: Windowed task trigger support (execute within time window)
- NEW: Comprehensive iOS test suite (38+ tests for ChainProgress, ChainExecutor, IosFileStorage)
- Improved iOS retry logic with max retry limits (prevents infinite loops)
- Enhanced iOS batch processing for efficient BGTask usage
- Production-grade error handling and logging improvements
- iOS documentation: Best practices and migration guides
v1.0.0 - Initial Stable Release
- Worker factory pattern for better extensibility
- Automatic iOS task ID validation from Info.plist
- Type-safe serialization extensions
- Unified API for Android and iOS
- File-based storage on iOS for better performance
- Smart exact alarm fallback on Android
- Heavy task support with foreground services
- Task chains with sequential and parallel execution
Requirements
- Kotlin 2.1.21 or higher
- Android: API 21+ (Android 5.0)
- iOS: 13.0+
- Gradle 8.0+
Contributing
Contributions are welcome. Please:
- Open an issue to discuss proposed changes
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
See CONTRIBUTING.md for details.
License
Copyright 2026 Brewkits
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Links
⭐ Star Us on GitHub!
If KMP WorkManager saves you time, please give us a star!
It helps other developers discover this project.
Made with ❤️ by Nguyễn Tuấn Việt at Brewkits
Support: datacenter111@gmail.com • Community: GitHub Issues
