diff --git a/CHANGELOG.md b/CHANGELOG.md index 459fd76..d2cccb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 1.1.0 - 2026-11-09 + +### Added + +- `Scheduler.jobStates(handle, replayFinished = false)`: states of one task, never completes on job cancellation. + Replays the state of a running job to new subscribers; with `replayFinished = true` it also replays the last + finished (success or error) job when nothing is running, so late subscribers get the result. +- `Scheduler.successResults(handle, replayFinished = false): Flow` and + `Scheduler.errors(handle, replayFinished = false): Flow`. +- `JobState.resultOf(handle): R?`: the job result typed by the task's result type, no cast at the call site. + `JobState` itself stays untyped (`result: Any?`), so 1.0.0 code compiles unchanged. +- `Scheduler.isRunning(handle)`: whether a job started with `start` / `startLatest` / `restart` is active. +- `observeStateChanges(handle, completeOnJobCancel)`: pass `false` to keep observing after a job is cancelled. +- README: remo 1.2.0 / 9.0.1 to reactive-tasks API map. + +### Fixed + +- `observeStateChanges(handle)` emits only states of `handle`'s jobs and completes only when a job of `handle` + is cancelled (it used to emit all tasks' states and close on any cancelled job). +- Default `onUncaughtException` printed task id and name swapped. + ## 1.0.0 - 2026-11-08 First public release, published to Maven Central as `ru.kode:reactive-tasks`. diff --git a/README.md b/README.md index 0005ea6..1031a7e 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A library for scheduling, executing and observing repeateble reactive tasks. Kotlin Multiplatform: JVM, Android, iOS (`iosX64`, `iosArm64`, `iosSimulatorArm64`). ```kotlin -implementation("ru.kode:reactive-tasks:1.0.0") +implementation("ru.kode:reactive-tasks:1.1.0") ``` # How to use @@ -83,11 +83,19 @@ scheduler.addTaskStateChangeListener(object : TaskStateChangeListener { } } -// -// There's also a simple utility which wraps listener -// into Flow. It is fairly simple implementation, if you need -// something more involved, check how observeStateChanges is implemented, -// use it as a reference +// +// Or observe one task as a Flow. Read a typed result with state.resultOf(handle): R? +// +val searchStates = scheduler.jobStates(searchTaskHandle) // replays a running job's state, never completes on cancel +val lastResult = scheduler.successResults(searchTaskHandle, replayFinished = true) // also replays the last finished result +val searchResults = scheduler.successResults(searchTaskHandle) // Flow, no casts +val searchErrors = scheduler.errors(searchTaskHandle) // Flow +val fetchRunning = scheduler.isRunning(fetchTaskHandle) + +// +// observeStateChanges completes on the first cancelled job of the task (pass completeOnJobCancel = false +// to keep observing). It is fairly simple implementation, if you need something more involved, +// check how it is implemented, use it as a reference // val taskStateChanges = scheduler.observeStateChanges(searchTaskHandle) runBlocking { @@ -131,59 +139,42 @@ reactive-tasks drops the `ReactiveModel` base class and `kotlin-result`, and add // before implementation("ru.kode:remo:1.2.0") // or ru.kode:remo:9.0.1, ru.kode.android:remo:9.1.0 // after -implementation("ru.kode:reactive-tasks:1.0.0") +implementation("ru.kode:reactive-tasks:1.1.0") ``` -## API map - -| remo | reactive-tasks | -|---|---| -| `class UserModel : ReactiveModel()` | `class UserModel(scheduler: Scheduler)`, no base class | -| `model.start(parentScope)` (1.x) / constructor scope (9.x), `Job.cancel()` to stop | `Scheduler(scope)`, cancel `scope` to stop | -| `scope.launch { }` inside the model | `scheduler.scope.launch { }` | -| `uncaughtExceptions: Flow` | `Scheduler(onUncaughtException = { taskId, name, e -> })` | -| `val fetch = task { id: String -> api.fetch(id) }` | `val fetch = scheduler.registerTask("fetch") { id: String -> api.fetch(id) }` | -| `task { -> api.fetch() }` | `registerTask("fetch") { _: Unit -> api.fetch() }`, `start(fetch, Unit)` | -| `task { a: A, b: B -> }` (2–3 params) | one argument: `registerTask("t") { (a, b): Pair -> }` or a data class | -| `fetch.start(id)`: `Job` | `scheduler.start(fetch, id)`: `JobHandle` | -| `job.cancel()` | `scheduler.cancel(jobHandle)` / `scheduler.cancel(fetch)` (all jobs of the task) | -| `QueueingStrategy.Disallow` (default: fails if a job runs) | no equivalent, `start` runs jobs in parallel | -| `QueueingStrategy.SkipNew` | check `isRunning(fetch)` (below) before `start` | -| — | `startLatest(fetch, id)`: cancels running jobs of the task (search-as-you-type) | -| — | `startSuspended(fetch, id)`: suspends until done, returns `JobState` | -| `WatchContext()` + `executeInModelScope { }` | `registerTask` + `start` | -| one `WatchContext` shared by several jobs (one loader) | several tasks, `merge(jobStates(a), jobStates(b))`, or one task with a sealed argument | -| `fetch.jobFlow.state`: `Idle` / `Running` | `jobStates(fetch).map { it.runState == RunState.Running }` | -| `fetch.jobFlow.successResults()` | `jobStates(fetch).filter { it.runState == RunState.FinishedSuccess }.map { it.result as R }` | -| `fetch.jobFlow.errors()` | `jobStates(fetch).filter { it.runState == RunState.FinishedError }.map { it.error!! }` | -| `fetch.jobFlow.results()`: `Result` | `JobState` with `runState`, `result`, `error` | -| `results(replayLast = true)` | no replay: `shareIn(scope, started, replay = 1)` or `stateIn`; last states are in `scheduler.taskJobState` | -| `StartScheduled.Lazily(...)` | subscribe first: `shareIn(...).onSubscription { scheduler.start(fetch, id) }` | -| `mapErrors {}` / `WatchContext(errorMapper = …)` | map in the flow, or catch inside the task body | - -## Observing one task - -`Scheduler.observeStateChanges(handle)` (1.0.0) emits states of **all** tasks of the scheduler and closes on the -first cancelled job of any task — `startLatest` cancels jobs, so the flow would end. Until it is fixed, observe with -this helper, which behaves like remo's `jobFlow`: +remo 1.2.0 and 9.x differ only in how a model gets its scope; tasks and `JobFlow` are the same. +Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. -```kotlin -@OptIn(ExperimentalUuidApi::class) -fun Scheduler.jobStates(task: TaskHandle<*, *>): Flow = callbackFlow { - val listener = object : TaskStateChangeListener { - override suspend fun onJobStateChanged(state: JobState) { - if (state.taskId == task.id) send(state) - } - - override fun onJobCancelled(taskId: Uuid, jobId: Uuid) = Unit - } - addTaskStateChangeListener(listener) - awaitClose { removeTaskStateChangeListener(listener) } -} +## API map -fun Scheduler.isRunning(task: TaskHandle<*, *>): Boolean = - taskJobState.values.any { it.taskId == task.id && it.runState == RunState.Running } -``` +| remo 1.2.0 | remo 9.0.1 | reactive-tasks 1.1.0 | +|---|---|---| +| `class M : ReactiveModel(dispatcher)` | `class M(scope) : ReactiveModel(scope)` | `class M(scheduler: Scheduler)`, no base class | +| `model.start(parentScope)`, `Job.cancel()` to stop | constructor `scope`, cancel it to stop | `Scheduler(scope)`, cancel `scope` to stop | +| `onPostStart()` | `init {}` (`onPostStart` deprecated) | `init {}` | +| `scope.launch {}` inside the model | same | `scheduler.scope.launch {}` | +| `uncaughtExceptions: Flow` | same | `Scheduler(onUncaughtException = { taskId, taskName, e -> })` | +| `ReactiveModel(errorMapper = …)`, `task(errorMapper = …)`, `mapErrors {}` | same | map in the flow: `errors(fetch).map { … }`, or catch inside the task body | +| `val fetch = task { id: String -> api.fetch(id) }` | same | `val fetch = scheduler.registerTask("fetch") { id: String -> api.fetch(id) }` | +| `task { -> api.fetch() }` (`Task0`) | same | `registerTask("fetch") { _: Unit -> api.fetch() }`, `start(fetch, Unit)` | +| `task { a: A, b: B -> }` (`Task2` / `Task3`) | same | one data class argument: `registerTask("t") { (a, b): Args -> }` | +| `taskIn(watchContext) { }`, `WatchContext.executeInModelScope { }` | same | `registerTask` + `start` | +| one `WatchContext` shared by several tasks | same | `merge(jobStates(a), jobStates(b))`, or one task with a sealed argument | +| `fetch.start(id)`: `Job` | same | `scheduler.start(fetch, id)`: `JobHandle` | +| `job.cancel()` | same | `scheduler.cancel(jobHandle)`, `scheduler.cancel(fetch)` (all jobs of the task) | +| `start(id, queueingStrategy = Disallow)` (default, throws if a job runs) | same | no equivalent, `start` runs jobs in parallel | +| `start(id, queueingStrategy = SkipNew)` | same | `if (!scheduler.isRunning(fetch)) scheduler.start(fetch, id)` | +| restart a running job with a new argument | same | `scheduler.startLatest(fetch, id)`: cancels running jobs of the task | +| re-run with the last argument | same | `scheduler.restart(fetch)` | +| `start(id, StartScheduled.Lazily())` | same | `flow { emit(scheduler.startSuspended(fetch, id)) }`, or `shareIn(…).onSubscription { scheduler.start(fetch, id) }` | +| — | — | `startSuspended(fetch, id)`: suspends until done, returns `JobState` (`state.resultOf(fetch)`: `R?`) | +| `fetch.jobFlow` | same | `scheduler.jobStates(fetch)`: `Flow` | +| `fetch.jobFlow.state`: `Idle` / `Running` | same | `jobStates(fetch).map { it.runState == RunState.Running }` (a running job is replayed on subscribe) | +| `fetch.jobFlow.successResults()` | same | `scheduler.successResults(fetch)`: `Flow` | +| `fetch.jobFlow.errors()` | same | `scheduler.errors(fetch)`: `Flow` | +| `fetch.jobFlow.results()`: `Result` | same | `jobStates(fetch)`: `JobState` with `runState`, `error`, `resultOf(fetch)`: `R?` | +| `results(replayLast = true)`, `successResults(replayLast = true)` | same | `jobStates(fetch, replayFinished = true)`, `successResults(fetch, replayFinished = true)` | +| `mapSuccessResults {}` | same | `successResults(fetch).map {}` | ## Example @@ -198,9 +189,7 @@ model.fetch.start(Sort.Ascending) // reactive-tasks class UserListModel(private val scheduler: Scheduler) { val fetch = scheduler.registerTask("fetch") { sort: Sort -> api.fetch(sort) } - val users: Flow> = scheduler.jobStates(fetch) - .filter { it.runState == RunState.FinishedSuccess } - .map { it.result as List } + val users: Flow> = scheduler.successResults(fetch) fun fetch(sort: Sort) = scheduler.start(fetch, sort) } ``` diff --git a/gradle.properties b/gradle.properties index 0e31d6e..4640391 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ kotlin.mpp.enableCInteropCommonization=true android.useAndroidX=true android.nonTransitiveRClass=true #Publishing -versionName=1.0.0 +versionName=1.1.0 pomGroupId=ru.kode pomName=Reactive Tasks pomDescription=Kotlin Multiplatform library for scheduling, executing and observing reactive tasks diff --git a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt index 8d6547e..cf7faa8 100644 --- a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt +++ b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt @@ -13,6 +13,9 @@ import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlin.coroutines.EmptyCoroutineContext @@ -91,7 +94,7 @@ enum class RunState { } /** - * A state of a job + * A state of a job. Use [resultOf] to read [result] typed by the task's result type */ @OptIn(ExperimentalUuidApi::class) data class JobState( @@ -185,8 +188,8 @@ class Scheduler( * (which is passed to the [registerTask]), because exceptions inside the "body" are caught * and stored in the [JobState#error] field */ - val onUncaughtException: (taskId: Uuid, taskName: String, error: Throwable) -> Unit = { name, id, e -> - println("warning: uncaught exception from task \"$name[$id]\"") + val onUncaughtException: (taskId: Uuid, taskName: String, error: Throwable) -> Unit = { taskId, taskName, e -> + println(uncaughtExceptionMessage(taskId, taskName)) e.printStackTrace() } ) { @@ -204,6 +207,16 @@ class Scheduler( */ val taskJobState: Map = _taskJobState + /** + * A map of taskId to the most recent state of a still running job of that task + */ + internal val runningTaskState: MutableMap = createConcurrentMutableMap() + + /** + * A map of taskId to the state of the most recently finished (success or error) job of that task + */ + internal val finishedTaskState: MutableMap = createConcurrentMutableMap() + private val stateChangeListeners: MutableList = createConcurrentMutableList() private fun createExceptionHandler(taskId: Uuid, taskName: String): CoroutineExceptionHandler { @@ -322,27 +335,44 @@ class Scheduler( } private suspend fun executeWrappedBody(handle: TaskHandle, jobId: Uuid, argument: A, tag: Any?): JobState { - val state = JobState(jobId = jobId, taskId = handle.id, argument = argument, tag = tag, runState = RunState.Running) - _taskJobState[jobId] = state - stateChangeListeners.forEach { it.onJobStateChanged(state) } - try { - val result = handle.body(argument) - val state = JobState(jobId = jobId, taskId = handle.id, argument = argument, tag = tag, runState = RunState.FinishedSuccess, result = result) + suspend fun publish(state: JobState): JobState { _taskJobState[jobId] = state + if (state.runState == RunState.Running) { + runningTaskState[handle.id] = state + } else { + finishedTaskState[handle.id] = state + forgetRunning(handle.id, jobId) + } stateChangeListeners.forEach { it.onJobStateChanged(state) } return state - } catch (e: Throwable) { - if (e is CancellationException) { - throw e - } else { - val state = JobState(jobId = jobId, taskId = handle.id, argument = argument, tag = tag, runState = RunState.FinishedError, error = e) - _taskJobState[jobId] = state - stateChangeListeners.forEach { it.onJobStateChanged(state) } - return state + } + val running = JobState(jobId = jobId, taskId = handle.id, argument = argument, tag = tag, runState = RunState.Running) + try { + publish(running) + return try { + publish(running.copy(runState = RunState.FinishedSuccess, result = handle.body(argument))) + } catch (e: Throwable) { + if (e is CancellationException) throw e + publish(running.copy(runState = RunState.FinishedError, error = e)) } + } catch (e: CancellationException) { + forgetRunning(handle.id, jobId) + throw e } } + private fun forgetRunning(taskId: Uuid, jobId: Uuid) { + if (runningTaskState[taskId]?.jobId == jobId) runningTaskState.remove(taskId) + } + + /** + * Returns true if a job started with [start], [startLatest] or [restart] for [handle] is still active. + * Jobs started with [startSuspended] are not counted. + */ + fun isRunning(handle: TaskHandle<*, *>): Boolean { + return handle.scope.coroutineContext.job.children.any() + } + /** * Restarts the task referenced by [handle]. * Reuses the argument of the most recent [start] call. @@ -406,9 +436,14 @@ class Scheduler( } } +@OptIn(ExperimentalUuidApi::class) +internal fun uncaughtExceptionMessage(taskId: Uuid, taskName: String): String { + return "warning: uncaught exception from task \"$taskName[$taskId]\"" +} + /** * A simple converter from callback-based observation (using [TaskStateChangeListener]) to reactive-based - * observation using [Flow]. + * observation using [Flow]. Emits states of jobs of the task represented by [handle] only. * * If you wish to do some action (for example starting a task with [Scheduler#start]) only after this flow * subscription is established, you can use some combination of "shareIn and/or replay and/or custom implementation @@ -420,20 +455,90 @@ class Scheduler( * * Note that if anything more complex or specific is required, you can always implement the functionality you * need in a similar fashion. + * + * @param completeOnJobCancel when true (the default), the flow completes with a [CancellationException] as soon as + * any job of this task is cancelled. Pass false to keep observing, e.g. when the task is started with + * [Scheduler#startLatest] which cancels previous jobs. Jobs of other tasks never complete the flow. + */ +fun Scheduler.observeStateChanges(handle: TaskHandle<*, *>, completeOnJobCancel: Boolean): Flow { + return stateChanges(handle, completeOnJobCancel, replay = Replay.None) +} + +/** + * Same as `observeStateChanges(handle, completeOnJobCancel = true)` */ -@OptIn(ExperimentalUuidApi::class) fun Scheduler.observeStateChanges(handle: TaskHandle<*, *>): Flow { + return observeStateChanges(handle, completeOnJobCancel = true) +} + +/** + * Emits states of jobs of the task represented by [handle], never completes on job cancellation. + * + * If the task has a running job at the moment of subscription, its [RunState.Running] state is emitted first, + * so a late subscriber does not miss it. + * + * @param replayFinished when true and no job is running, the state of the most recently finished (success or + * error) job is replayed, so a subscriber that comes after the job completed still receives its result. + * Cancelled jobs are never replayed. + */ +fun Scheduler.jobStates(handle: TaskHandle<*, *>, replayFinished: Boolean = false): Flow { + return stateChanges(handle, completeOnJobCancel = false, replay = if (replayFinished) Replay.Last else Replay.Running) +} + +private enum class Replay { None, Running, Last } + +/** + * Emits results of successfully finished jobs of the task represented by [handle], see [jobStates] + */ +fun Scheduler.successResults(handle: TaskHandle<*, R>, replayFinished: Boolean = false): Flow { + @Suppress("UNCHECKED_CAST") + return jobStates(handle, replayFinished).filter { it.runState == RunState.FinishedSuccess }.map { it.resultOf(handle) as R } +} + +/** + * Returns [JobState.result] typed by the result type of [handle], the task this state belongs to. + * Null if the job has not finished successfully. + */ +@OptIn(ExperimentalUuidApi::class) +fun JobState.resultOf(handle: TaskHandle<*, R>): R? { + require(taskId == handle.id) { "state of task $taskId does not belong to task ${handle.id}" } + @Suppress("UNCHECKED_CAST") + return result as R? +} + +/** + * Emits errors of failed jobs of the task represented by [handle], see [jobStates] + */ +fun Scheduler.errors(handle: TaskHandle<*, *>, replayFinished: Boolean = false): Flow { + return jobStates(handle, replayFinished).mapNotNull { it.error } +} + +@OptIn(ExperimentalUuidApi::class) +private fun Scheduler.stateChanges( + handle: TaskHandle<*, *>, + completeOnJobCancel: Boolean, + replay: Replay, +): Flow { return callbackFlow { val listener = object : TaskStateChangeListener { override suspend fun onJobStateChanged(state: JobState) { - send(state) + if (state.taskId == handle.id) send(state) } override fun onJobCancelled(taskId: Uuid, jobId: Uuid) { - cancel(CancellationException("Task taskId=$taskId, jobId=$jobId was cancelled")) + if (completeOnJobCancel && taskId == handle.id) { + cancel(CancellationException("Task taskId=$taskId, jobId=$jobId was cancelled")) + } } } - this@observeStateChanges.addTaskStateChangeListener(listener) - awaitClose { this@observeStateChanges.removeTaskStateChangeListener(listener) } + this@stateChanges.addTaskStateChangeListener(listener) + // read after subscribing: a state changing in between may arrive twice, but is never lost + val replayed = when (replay) { + Replay.None -> null + Replay.Running -> runningTaskState[handle.id] + Replay.Last -> runningTaskState[handle.id] ?: finishedTaskState[handle.id] + } + replayed?.let { listener.onJobStateChanged(it) } + awaitClose { this@stateChanges.removeTaskStateChangeListener(listener) } } } diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt index c0de13f..a615e66 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -15,22 +15,26 @@ import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.uuid.ExperimentalUuidApi +import kotlin.uuid.Uuid class ObserveStateChangesTest { - private class Collected(val job: Job) { + private class Collected { + lateinit var job: Job val states = mutableListOf() var error: Throwable? = null } private fun TestScope.collect(flow: Flow): Collected { - lateinit var collected: Collected + val collected = Collected() // unconfined: advanceUntilIdle() does not run backgroundScope work, so the collector must resume eagerly - val job = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + collected.job = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { try { flow.collect { collected.states += it } } catch (e: CancellationException) { @@ -38,7 +42,6 @@ class ObserveStateChangesTest { throw e } } - collected = Collected(job) runCurrent() // subscribe before the test starts anything return collected } @@ -95,20 +98,142 @@ class ObserveStateChangesTest { } @Test - fun emitsStatesOfOtherTasks() = runTest { + fun ignoresOtherTasks() = runTest { val scheduler = testScheduler() val observed = scheduler.registerTask("observed") { _: Int -> } val other = scheduler.registerTask("other") { _: Int -> delay(1000) } val collected = collect(scheduler.observeStateChanges(observed)) - // quirk: no filtering by handle, other tasks' states leak into the flow... val otherJob = scheduler.start(other, 1) runCurrent() - assertEquals(listOf(other.id), collected.states.map { it.taskId }) - - // ...and cancelling another task closes it scheduler.cancel(otherJob) advanceUntilIdle() - assertIs(collected.error) + scheduler.start(observed, 1) + advanceUntilIdle() + + assertNull(collected.error) + assertEquals(listOf(observed.id, observed.id), collected.states.map { it.taskId }) + } + + @Test + fun completeOnJobCancelFalseKeepsObserving() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { s: String -> delay(1000); s } + val collected = collect(scheduler.observeStateChanges(task, completeOnJobCancel = false)) + + scheduler.startLatest(task, "a") + runCurrent() + scheduler.startLatest(task, "b") + advanceUntilIdle() + + assertNull(collected.error) + assertEquals(listOf("a", "b", "b"), collected.states.map { it.argument }) + assertEquals("b", collected.states.last().result) + } + + @Test + fun jobStatesReplaysRunningState() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val job = scheduler.start(task, 1) + runCurrent() + + val collected = collect(scheduler.jobStates(task)) + scheduler.cancel(job) + advanceUntilIdle() + + assertEquals(listOf(job.id to RunState.Running), collected.states.map { it.jobId to it.runState }) + assertNull(collected.error) // jobStates never completes on job cancellation + } + + @Test + fun jobStatesDoesNotReplayFinishedOrCancelledJobs() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } + scheduler.start(task, 1) + advanceUntilIdle() + val cancelled = scheduler.start(task, 2) + runCurrent() + scheduler.cancel(cancelled) + advanceUntilIdle() + + val collected = collect(scheduler.jobStates(task)) + + assertTrue(collected.states.isEmpty()) + } + + @Test + fun jobStatesReplayFinishedReplaysLastFinishedJob() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> delay(1000); if (n < 0) error("negative") else n } + scheduler.start(task, 1) + advanceUntilIdle() + val cancelled = scheduler.start(task, 2) + runCurrent() + scheduler.cancel(cancelled) + advanceUntilIdle() + + val states = collect(scheduler.jobStates(task, replayFinished = true)).states + assertEquals(listOf(RunState.FinishedSuccess), states.map { it.runState }) + assertEquals(1, states.single().resultOf(task)) + + val results = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + scheduler.successResults(task, replayFinished = true).collect { results += it } + } + runCurrent() + assertEquals(listOf(1), results) + + scheduler.start(task, -1) + advanceUntilIdle() + val errors = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + scheduler.errors(task, replayFinished = true).collect { errors += it } + } + runCurrent() + assertEquals(listOf("negative"), errors.map { it.message }) + } + + @Test + fun typedResultsAndErrors() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> if (n < 0) error("negative") else n * 2 } + val results = mutableListOf() + val errors = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { scheduler.successResults(task).collect { results += it } } + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { scheduler.errors(task).collect { errors += it } } + runCurrent() + + scheduler.start(task, 2) + scheduler.start(task, -1) + advanceUntilIdle() + val state = scheduler.startSuspended(task, 5) + val doubled: Int? = state.resultOf(task) + val other = scheduler.registerTask("other") { _: Unit -> } + assertFailsWith { state.resultOf(other) } + + assertEquals(listOf(4, 10), results) + assertEquals(listOf("negative"), errors.map { it.message }) + assertEquals(10, doubled) + } + + @Test + fun defaultUncaughtExceptionMessageHasNameThenId() { + val id = Uuid.random() + assertEquals("warning: uncaught exception from task \"fetch[$id]\"", uncaughtExceptionMessage(id, "fetch")) + } + + @Test + fun isRunningTracksStartedJobs() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + assertFalse(scheduler.isRunning(task)) + + scheduler.start(task, 1) + runCurrent() + assertTrue(scheduler.isRunning(task)) + + advanceUntilIdle() + assertFalse(scheduler.isRunning(task)) } }