Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 1.2.0 - 2026-11-10

### Added

- `Scheduler.finishedStates(handle, replayLast = false): Flow<JobState>`: 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<Boolean>`: `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
Expand Down
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<R>, no casts
val searchErrors = scheduler.errors(searchTaskHandle) // Flow<Throwable>
val searchFinished = scheduler.finishedStates(searchTaskHandle, replayLast = true) // finished states only
val searchProgress = scheduler.runningStates(searchTaskHandle) // Flow<Boolean>, false after a cancel
val fetchRunning = scheduler.isRunning(fetchTaskHandle)

//
Expand Down Expand Up @@ -139,15 +141,15 @@ 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.
Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle<A, R>`.

## 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 |
Expand All @@ -169,11 +171,12 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle<A, R>`.
| `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<JobState>` |
| `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<Boolean>`, current value on subscribe, `false` after a cancel |
| `fetch.jobFlow.successResults()` | same | `scheduler.successResults(fetch)`: `Flow<R>` |
| `fetch.jobFlow.errors()` | same | `scheduler.errors(fetch)`: `Flow<Throwable>` |
| `fetch.jobFlow.results()`: `Result<R, Throwable>` | 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
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -219,6 +222,11 @@ class Scheduler(

private val stateChangeListeners: MutableList<TaskStateChangeListener> = 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)
Expand Down Expand Up @@ -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<Any?, Any?>,
Expand Down Expand Up @@ -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<JobState> {
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<Boolean> {
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 <R> Scheduler.successResults(handle: TaskHandle<*, R>, replayFinished: Boolean = false): Flow<R> {
@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 }
}

/**
Expand All @@ -507,10 +552,13 @@ fun <R> 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<Throwable> {
return jobStates(handle, replayFinished).mapNotNull { it.error }
return finishedStates(handle, replayFinished).mapNotNull { it.error }
}

@OptIn(ExperimentalUuidApi::class)
Expand All @@ -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) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -46,6 +48,13 @@ class ObserveStateChangesTest {
return collected
}

private fun <T> TestScope.values(flow: Flow<T>): List<T> {
val values = mutableListOf<T>()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { flow.collect { values += it } }
runCurrent()
return values
}

@Test
fun emitsRunningThenSuccess() = runTest {
val scheduler = testScheduler()
Expand Down Expand Up @@ -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<Boolean>()
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)
}
}
Loading