TaskRegistry

Thread-safe global registry mapping task IDs to their suspend handler functions.

Tasks must be registered before being enqueued. KMPWorker intentionally avoids reflection and annotation processing in favour of explicit registration.

Threading contract: register() and unregister() should be called from the main thread during app initialization, before any background tasks start. This matches the standard pattern used by WorkManager and BGTaskScheduler — workers are always registered at startup, not mid-execution.

Usage:

TaskRegistry.register("sync-users") { ctx ->
println("Running task ${ctx.taskId}, attempt ${ctx.retryCount}")
repository.syncUsers()
}
TaskRegistry.execute("sync-users", TaskExecutionContext("sync-users", retryCount = 0))

Functions

Link copied to clipboard
fun clearAll()

Clears all registered handlers. For use in tests only.

Link copied to clipboard
suspend fun execute(id: String, context: TaskExecutionContext = TaskExecutionContext(id))

Executes the registered handler for the given task ID with the provided context.

Link copied to clipboard
fun handlerFor(id: String): suspend TaskExecutionContext.() -> Unit?

Returns the handler for id, or null if not registered. Used by TaskChainExecutor.

Link copied to clipboard

Returns true if a handler is registered for the given task ID.

Link copied to clipboard
fun register(id: String, block: suspend TaskExecutionContext.() -> Unit)

Registers a suspend handler for the given task ID.

Link copied to clipboard

Returns all currently registered task IDs. Snapshot — safe to iterate.

Link copied to clipboard

Removes the handler for the given task ID.