TaskMonitor

Broadcasts task state changes across the application.

Features

  • replay=1: New collectors immediately receive the last known state for a task.

  • extraBufferCapacity=64: Emitters never block due to slow collectors.

  • Persistent EventStore: Install an EventStore via install to persist terminal states to disk. Call replayPendingEvents at app startup to recover missed completions.

Usage

// App startup:
TaskMonitor.install(SqlDelightEventStore(database))
TaskMonitor.replayPendingEvents() // replay missed completions from last session

// Observe:
TaskMonitor.observe("sync-users").collect { state -> ... }

// Emit:
TaskMonitor.emit("sync-users", TaskState.Running())

Functions

Link copied to clipboard
suspend fun cancel(taskId: String)

Emits TaskState.Cancelled for the given task ID and removes any stored events.

Link copied to clipboard
suspend fun emit(taskId: String, state: TaskState)

Emits a new state for the given task ID. Terminal states are automatically persisted to the EventStore if installed. Safe to call from any coroutine context.

Link copied to clipboard
fun install(store: EventStore)

Installs an EventStore that will receive all terminal state events. Terminal states are: TaskState.Success, TaskState.Cancelled, and TaskState.Failed with willRetry = false.

Link copied to clipboard
fun observe(taskId: String): Flow<TaskState>

Returns a Flow of TaskState updates filtered to the given task ID. The flow never completes — it remains active for the lifetime of the app.

Link copied to clipboard

Returns a Flow of ALL task state updates as (taskId, TaskState) pairs. Useful for global dashboards, monitoring, and TaskChainExecutor.

Link copied to clipboard
suspend fun pruneOldEvents(olderThanMillis: Long = 7 * 24 * 60 * 60 * 1_000L)

Prunes persisted events older than olderThanMillis ms that have already been replayed. Call once per session to keep storage bounded (e.g., at app startup after replay). No-op if no EventStore is installed.

Link copied to clipboard
suspend fun replayPendingEvents()

Replays all persisted terminal events that have not yet been delivered. Call at app startup (e.g., in Application.onCreate or AppDelegate) to ensure the UI reflects task completions that happened while the app was terminated.

Link copied to clipboard
fun resetAll()

Public alias for reset. Accessible from androidTest and integration test modules.

Link copied to clipboard
fun tryEmit(taskId: String, state: TaskState): Boolean

Emits a state without suspending. Drops the event if the buffer is full. Prefer emit when a coroutine context is available. Note: Does NOT persist to EventStore — use emit for terminal states.