From 4e086223a8eeefdc3234cd6bb39a93cb5f12ae6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=BB=D1=8C=D1=8F=20=D0=9D=D0=B5=D0=BA=D1=80=D0=B0?= =?UTF-8?q?=D1=81=D0=BE=D0=B2?= Date: Tue, 10 Nov 2026 09:14:59 +0000 Subject: [PATCH] 1.2.0: remo replay and progress semantics - finishedStates(handle, replayLast): finished states only, replays the last finished job even while another one runs (remo results(replayLast)) - runningStates(handle): isRunning as a Flow, goes false after a cancel (remo JobFlow.state for progress) - successResults/errors(replayFinished = true) replay the last finished job during a re-run, then filter, as remo did --- CHANGELOG.md | 18 +++ README.md | 13 +- gradle.properties | 2 +- .../ru/kode/reactivetasks/ReactiveTasks.kt | 59 +++++++- .../reactivetasks/ObserveStateChangesTest.kt | 130 ++++++++++++++++++ 5 files changed, 211 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2cccb1..06f6d11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.2.0 - 2026-11-10 + +### Added + +- `Scheduler.finishedStates(handle, replayLast = false): Flow`: only `FinishedSuccess` and + `FinishedError` states of the task, never completes on job cancellation. With `replayLast = true` the last + finished job is replayed first, even while another job runs. The remo `results(replayLast)` equivalent. +- `Scheduler.runningStates(handle): Flow`: `isRunning(handle)` on subscription, then on every job start, + finish and cancellation (including cancelling the scheduler scope). For progress indicators, replaces remo's + `JobFlow.state`. + +### Changed + +- `successResults(handle, replayFinished = true)` and `errors(handle, replayFinished = true)` replay the last + finished job even while another job of the task runs (they used to replay nothing until the running job finished). + As in remo, the last finished state is replayed and then filtered: after an error `successResults` replays + nothing and `errors` replays the error. + ## 1.1.0 - 2026-11-09 ### Added diff --git a/README.md b/README.md index 1031a7e..57dcb9e 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.1.0") +implementation("ru.kode:reactive-tasks:1.2.0") ``` # How to use @@ -90,6 +90,8 @@ val searchStates = scheduler.jobStates(searchTaskHandle) // replays a runni 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 searchFinished = scheduler.finishedStates(searchTaskHandle, replayLast = true) // finished states only +val searchProgress = scheduler.runningStates(searchTaskHandle) // Flow, false after a cancel val fetchRunning = scheduler.isRunning(fetchTaskHandle) // @@ -139,7 +141,7 @@ 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.1.0") +implementation("ru.kode:reactive-tasks:1.2.0") ``` remo 1.2.0 and 9.x differ only in how a model gets its scope; tasks and `JobFlow` are the same. @@ -147,7 +149,7 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. ## API map -| remo 1.2.0 | remo 9.0.1 | reactive-tasks 1.1.0 | +| remo 1.2.0 | remo 9.0.1 | reactive-tasks 1.2.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 | @@ -169,11 +171,12 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. | `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.state`: `Idle` / `Running` (progress) | same | `scheduler.runningStates(fetch)`: `Flow`, current value on subscribe, `false` after a cancel | | `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)` | +| `results(replayLast = true)` | same | `scheduler.finishedStates(fetch, replayLast = true)`: replays the last finished job even while a new one runs | +| `successResults(replayLast = true)`, `errors(replayLast = true)` | same | `successResults(fetch, replayFinished = true)`, `errors(fetch, replayFinished = true)` | | `mapSuccessResults {}` | same | `successResults(fetch).map {}` | ## Example diff --git a/gradle.properties b/gradle.properties index 4640391..2a97e9d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ kotlin.mpp.enableCInteropCommonization=true android.useAndroidX=true android.nonTransitiveRClass=true #Publishing -versionName=1.1.0 +versionName=1.2.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 cf7faa8..0be801e 100644 --- a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt +++ b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt @@ -10,9 +10,12 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull @@ -219,6 +222,11 @@ class Scheduler( private val stateChangeListeners: MutableList = createConcurrentMutableList() + /** + * Called with a taskId when a job of that task is launched or completes (normally or by cancellation) + */ + internal val runningChangeListeners: MutableList<(taskId: Uuid) -> Unit> = createConcurrentMutableList() + private fun createExceptionHandler(taskId: Uuid, taskName: String): CoroutineExceptionHandler { return CoroutineExceptionHandler { _, e -> onUncaughtException(taskId, taskName, e) @@ -320,12 +328,15 @@ class Scheduler( } executeWrappedBody(handle, jobId, argument, tag) } + runningChangeListeners.forEach { it(handle.id) } + // the job is already detached from the task scope here, so isRunning does not count it job.invokeOnCompletion { cause -> if (cause is CancellationException) { stateChangeListeners.forEach { it.onJobCancelled(handle.id, jobId) } } + runningChangeListeners.forEach { it(handle.id) } } return JobHandle( handle as TaskHandle, @@ -485,14 +496,48 @@ fun Scheduler.jobStates(handle: TaskHandle<*, *>, replayFinished: Boolean = fals return stateChanges(handle, completeOnJobCancel = false, replay = if (replayFinished) Replay.Last else Replay.Running) } -private enum class Replay { None, Running, Last } +private enum class Replay { None, Running, Finished, Last } /** - * Emits results of successfully finished jobs of the task represented by [handle], see [jobStates] + * Emits only [RunState.FinishedSuccess] and [RunState.FinishedError] states of jobs of the task represented by + * [handle], never completes on job cancellation. + * + * @param replayLast when true, the state of the most recently finished job is replayed first, even while another + * job of the task is running. Cancelled jobs are never replayed. + */ +fun Scheduler.finishedStates(handle: TaskHandle<*, *>, replayLast: Boolean = false): Flow { + return stateChanges(handle, completeOnJobCancel = false, replay = if (replayLast) Replay.Finished else Replay.None) + .filter { it.runState == RunState.FinishedSuccess || it.runState == RunState.FinishedError } +} + +/** + * Emits [Scheduler.isRunning] for [handle] on subscription and then whenever it changes: a job is started, + * finishes or is cancelled (including by cancelling the scheduler scope). + * Jobs started with [Scheduler.startSuspended] are not counted. + */ +@OptIn(ExperimentalUuidApi::class) +fun Scheduler.runningStates(handle: TaskHandle<*, *>): Flow { + return callbackFlow { + val listener: (Uuid) -> Unit = { taskId -> if (taskId == handle.id) trySend(Unit) } + runningChangeListeners.add(listener) + send(Unit) + awaitClose { runningChangeListeners.remove(listener) } + } + .buffer(Channel.CONFLATED) + // read on collection, so concurrent changes can not be emitted out of order + .map { isRunning(handle) } + .distinctUntilChanged() +} + +/** + * Emits results of successfully finished jobs of the task represented by [handle]. + * + * @param replayFinished when true, the last finished job is replayed first if it succeeded, even while another + * job of the task is running. If the last finished job failed, nothing is replayed. See [finishedStates] */ 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 } + return finishedStates(handle, replayFinished).filter { it.runState == RunState.FinishedSuccess }.map { it.resultOf(handle) as R } } /** @@ -507,10 +552,13 @@ fun JobState.resultOf(handle: TaskHandle<*, R>): R? { } /** - * Emits errors of failed jobs of the task represented by [handle], see [jobStates] + * Emits errors of failed jobs of the task represented by [handle]. + * + * @param replayFinished when true, the last finished job is replayed first if it failed, even while another + * job of the task is running. If the last finished job succeeded, nothing is replayed. See [finishedStates] */ fun Scheduler.errors(handle: TaskHandle<*, *>, replayFinished: Boolean = false): Flow { - return jobStates(handle, replayFinished).mapNotNull { it.error } + return finishedStates(handle, replayFinished).mapNotNull { it.error } } @OptIn(ExperimentalUuidApi::class) @@ -536,6 +584,7 @@ private fun Scheduler.stateChanges( val replayed = when (replay) { Replay.None -> null Replay.Running -> runningTaskState[handle.id] + Replay.Finished -> finishedTaskState[handle.id] Replay.Last -> runningTaskState[handle.id] ?: finishedTaskState[handle.id] } replayed?.let { listener.onJobStateChanged(it) } diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt index a615e66..b026d93 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -3,11 +3,13 @@ package ru.kode.reactivetasks import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle @@ -46,6 +48,13 @@ class ObserveStateChangesTest { return collected } + private fun TestScope.values(flow: Flow): List { + val values = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { flow.collect { values += it } } + runCurrent() + return values + } + @Test fun emitsRunningThenSuccess() = runTest { val scheduler = testScheduler() @@ -236,4 +245,125 @@ class ObserveStateChangesTest { advanceUntilIdle() assertFalse(scheduler.isRunning(task)) } + + @Test + fun successResultsReplayDuringReRunReturnsPreviousResult() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } + scheduler.start(task, 1) + advanceUntilIdle() + scheduler.start(task, 2) + runCurrent() + + val results = values(scheduler.successResults(task, replayFinished = true)) + assertEquals(listOf(1), results) + + advanceUntilIdle() + assertEquals(listOf(1, 2), results) + } + + @Test + fun replayAfterErrorReplaysErrorOnly() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> if (n < 0) error("negative") else n } + scheduler.start(task, 1) + scheduler.start(task, -1) + advanceUntilIdle() + + assertEquals(emptyList(), values(scheduler.successResults(task, replayFinished = true))) + assertEquals(listOf("negative"), values(scheduler.errors(task, replayFinished = true)).map { it.message }) + } + + @Test + fun finishedStatesReplaysLastFinishedDuringRunningJob() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } + scheduler.start(task, 1) + advanceUntilIdle() + scheduler.start(task, 2) + runCurrent() + + val collected = collect(scheduler.finishedStates(task, replayLast = true)) + assertEquals(listOf(RunState.FinishedSuccess), collected.states.map { it.runState }) + assertEquals(1, collected.states.single().resultOf(task)) + + val cancelled = scheduler.start(task, 3) + runCurrent() + scheduler.cancel(cancelled) + advanceUntilIdle() + assertEquals(listOf(1, 2), collected.states.map { it.resultOf(task) }) + assertTrue(collected.job.isActive) + } + + @Test + fun noReplayWhenReplayIsOff() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { n: Int -> if (n < 0) error("negative") else n } + scheduler.start(task, 1) + advanceUntilIdle() + + assertTrue(collect(scheduler.finishedStates(task)).states.isEmpty()) + assertEquals(emptyList(), values(scheduler.successResults(task))) + scheduler.start(task, -1) + advanceUntilIdle() + assertEquals(emptyList(), values(scheduler.errors(task))) + } + + @Test + fun runningStatesGoesFalseAfterCancel() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val runningOnCancel = mutableListOf() + scheduler.addTaskStateChangeListener(object : TaskStateChangeListener { + override suspend fun onJobStateChanged(state: JobState) = Unit + override fun onJobCancelled(taskId: Uuid, jobId: Uuid) { + runningOnCancel += scheduler.isRunning(task) + } + }) + val running = values(scheduler.runningStates(task)) + assertEquals(listOf(false), running) + + scheduler.start(task, 1) + runCurrent() + assertEquals(listOf(false, true), running) + + scheduler.cancel(task) + runCurrent() + // the cancelled job is no longer counted when onJobCancelled fires + assertEquals(listOf(false), runningOnCancel) + assertEquals(listOf(false, true, false), running) + } + + @Test + fun runningStatesStaysTrueWhenStartLatestReplacesJob() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val running = values(scheduler.runningStates(task)) + + val first = scheduler.start(task, 1) + runCurrent() + scheduler.startLatest(task, 2) + runCurrent() + assertEquals(listOf(first.id), listener.cancelled.map { it.jobId }) + assertEquals(listOf(false, true), running) + + advanceUntilIdle() + assertEquals(listOf(false, true, false), running) + } + + @Test + fun runningStatesGoesFalseWhenSchedulerScopeIsCancelled() = runTest { + val parent = Job() + val scheduler = Scheduler(CoroutineScope(parent), StandardTestDispatcher(testScheduler), UncaughtRecorder().handler) + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val running = values(scheduler.runningStates(task)) + + scheduler.start(task, 1) + runCurrent() + parent.cancel() + advanceUntilIdle() + + assertEquals(listOf(false, true, false), running) + } }