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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
# Changelog

## 2.0.1 - 2026-11-12

### Fixed

- `launch`, `launchLatest`, `launchIfIdle`, `start`, `startIfIdle` threw `NullPointerException` on JVM/Android when
the argument was `null`. A `null` argument now works everywhere, and `relaunch` re-runs a job with a `null` argument
instead of returning `JobHandle.NIL`.
- Memory leak: a scheduler kept the argument and the state of every job ever started. The argument is now stored in
the `JobHandle`, and `Scheduler.taskJobState` keeps only the last finished job of each task (plus jobs which are
still running). States of older finished jobs and of cancelled jobs are removed. Read finished states with
`finishedStates` / `results` instead of looking up old job ids in `taskJobState`.
- A job could get dropped and `start` could hang forever when an observer of the task (`results`, `finishedStates`,
...) started the next job from inside its collector. State updates to observers no longer suspend the job which
publishes them.

## 2.0.0 - 2026-11-12

### Changed (breaking)
Expand Down
6 changes: 3 additions & 3 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:2.0.0")
implementation("ru.kode:reactive-tasks:2.0.1")
```

# How to use
Expand Down Expand Up @@ -172,15 +172,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:2.0.0")
implementation("ru.kode:reactive-tasks:2.0.1")
```

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 2.0.0 |
| remo 1.2.0 | remo 9.0.1 | reactive-tasks 2.0.1 |
|---|---|---|
| `class M : ReactiveModel(dispatcher)` | `class M(scope) : ReactiveModel(scope)` | `class M(scheduler: Scheduler)`, no base class |
| `model.start(parentScope)`, `Job.cancel()` to stop, can be started again with a new scope | constructor `scope`, cancel it to stop | `Scheduler(scope)`, cancel `scope` to stop for good; to stop and start again: `scheduler.bindTo(parentScope)` on each start |
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=2.0.0
versionName=2.0.1
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 @@ -61,6 +61,7 @@ class JobHandle(
val taskHandle: TaskHandle<Any?, Any?>,
val id: Uuid,
internal val job: Job,
internal val argument: Any? = null,
) {
companion object {
/**
Expand Down Expand Up @@ -200,17 +201,17 @@ class Scheduler(
e.printStackTrace()
}
) {
// TODO use configurable entry count?
/**
* A map from either JobHandle.id or TaskHandle.id to an argument object.
* A map from TaskHandle.id to a single-element list holding the most recent argument (a list, because
* concurrent maps do not accept null values and null is a valid argument).
*/
private val argumentCache: MutableMap<Uuid, Any?> = createConcurrentMutableMap()
private val lastArgument: MutableMap<Uuid, List<Any?>> = createConcurrentMutableMap()

// TODO evict states after some time/entry-count?
private val _taskJobState: MutableMap<Uuid, JobState> = createConcurrentMutableMap()

/**
* A map of jobId to task job states
* A map of jobId to task job states. Only the last finished job of each task is kept, plus jobs which are still
* running. States of older finished jobs and of cancelled jobs are removed.
*/
val taskJobState: Map<Uuid, JobState> = _taskJobState

Expand Down Expand Up @@ -320,8 +321,7 @@ class Scheduler(
*/
suspend fun <A, R> start(handle: TaskHandle<A, R>, argument: A, tag: Any? = null): JobState {
val jobId = Uuid.random()
argumentCache.put(jobId, argument as Any?)
argumentCache.put(handle.id, argument as Any?)
lastArgument[handle.id] = listOf(argument)
return executeWrappedBody(handle, jobId, argument, tag)
}

Expand Down Expand Up @@ -374,8 +374,7 @@ class Scheduler(

private fun <A> startInternal(handle: TaskHandle<A, *>, argument: A, tag: Any?, cancelPrevious: Boolean): JobHandle {
val jobId = Uuid.random()
argumentCache.put(jobId, argument as Any?)
argumentCache.put(handle.id, argument as Any?)
lastArgument[handle.id] = listOf(argument)
// NOTE @dz there can be a race if children will change between we get them here and
// before new job gets scheduled
val previousJobs = handle.scope.coroutineContext.job.children.toList()
Expand All @@ -401,6 +400,7 @@ class Scheduler(
handle as TaskHandle<Any?, Any?>,
jobId,
job,
argument,
)
}

Expand All @@ -410,7 +410,8 @@ class Scheduler(
if (state.runState == RunState.Running) {
runningTaskState[handle.id] = state
} else {
finishedTaskState[handle.id] = state
// only the last finished job of a task is kept
finishedTaskState.put(handle.id, state)?.let { if (it.jobId != jobId) _taskJobState.remove(it.jobId) }
forgetRunning(handle.id, jobId)
}
stateChangeListeners.forEach { it.onJobStateChanged(state) }
Expand All @@ -427,6 +428,7 @@ class Scheduler(
}
} catch (e: CancellationException) {
forgetRunning(handle.id, jobId)
_taskJobState.remove(jobId)
throw e
}
}
Expand All @@ -449,13 +451,9 @@ class Scheduler(
* Note that there is an overload which accepts [JobHandle] instead and it will use the argument from the particular job start.
*/
fun <A, R> relaunch(handle: TaskHandle<A, R>): JobHandle {
val last = lastArgument[handle.id] ?: return JobHandle.NIL
@Suppress("UNCHECKED_CAST")
val arg = argumentCache[handle.id] as? A?
return if (arg != null) {
launch(handle, arg)
} else {
JobHandle.NIL
}
return launch(handle, last[0] as A)
}

/**
Expand All @@ -464,12 +462,8 @@ class Scheduler(
* Note that there is an overload which accepts [TaskHandle] instead and it will use the argument from the most recent task start.
*/
fun relaunch(handle: JobHandle): JobHandle {
val arg = argumentCache[handle.id]
return if (arg != null) {
launch(handle.taskHandle, arg)
} else {
JobHandle.NIL
}
if (handle.id == Uuid.NIL) return JobHandle.NIL
return launch(handle.taskHandle, handle.argument)
}

/**
Expand Down Expand Up @@ -653,7 +647,8 @@ private fun Scheduler.stateChanges(
return callbackFlow {
val listener = object : TaskStateChangeListener {
override suspend fun onJobStateChanged(state: JobState) {
if (state.taskId == handle.id) send(state)
// never suspends and never throws into the job which publishes the state
if (state.taskId == handle.id) trySend(state)
}

override fun onJobCancelled(taskId: Uuid, jobId: Uuid) {
Expand All @@ -672,5 +667,5 @@ private fun Scheduler.stateChanges(
}
replayed?.let { listener.onJobStateChanged(it) }
awaitClose { this@stateChanges.removeTaskStateChangeListener(listener) }
}
}.buffer(Channel.UNLIMITED)
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
Expand Down Expand Up @@ -366,4 +367,29 @@ class ObserveStateChangesTest {

assertEquals(listOf(false, true, false), running)
}

@Test
fun observerStartingNextJobOnResultDoesNotDropJobs() = runTest {
val scheduler = testScheduler()
val ran = mutableListOf<Int>()
val task = scheduler.registerTask("chain") { n: Int -> ran += n; n }
// observer A, subscribed first
val a = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
scheduler.results(task, replayLast = false).first()
}
// observer B starts the next job when the first result arrives and waits for it
var second: JobState? = null
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
scheduler.results(task, replayLast = false).first()
second = scheduler.start(task, 2)
}
runCurrent()

scheduler.launch(task, 1)
advanceUntilIdle()

assertTrue(a.isCompleted)
assertEquals(listOf(1, 2), ran)
assertEquals(RunState.FinishedSuccess, second?.runState)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
Expand Down Expand Up @@ -165,8 +166,9 @@ class SchedulerTest {
assertEquals(RunState.Running, scheduler.taskJobState.getValue(second.id).runState)

advanceUntilIdle()
assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(first.id).runState)
assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(second.id).runState)
// only the last finished job of a task is kept in taskJobState
assertEquals(1, scheduler.taskJobState.size)
assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.values.single().runState)
}

@Test
Expand Down Expand Up @@ -218,8 +220,9 @@ class SchedulerTest {
listener.events,
)
assertTrue(first.job.isCancelled)
// quirk: a cancelled job's state stays Running forever
assertEquals(RunState.Running, scheduler.taskJobState.getValue(first.id).runState)
// state of a cancelled job is removed, only the last finished job is kept
assertNull(scheduler.taskJobState[first.id])
assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(second.id).runState)
}

// endregion
Expand Down Expand Up @@ -326,20 +329,54 @@ class SchedulerTest {
}

@Test
fun restartAfterNullArgument() = runTest {
fun nullArgumentWorksEverywhere() = runTest {
val scheduler = testScheduler()
val task = scheduler.registerTask("nullable") { _: String? -> }

val started = runCatching { scheduler.launch(task, null) }
// quirk: JVM/Android argumentCache is a ConcurrentHashMap, which rejects null values, so start throws NPE.
// iOS LockedMap accepts null, but restart treats a null argument as "never started" and returns NIL.
val error = started.exceptionOrNull()
if (error != null) {
assertIs<NullPointerException>(error)
} else {
assertSame(JobHandle.NIL, scheduler.relaunch(task))
assertSame(JobHandle.NIL, scheduler.relaunch(started.getOrThrow()))
}
val seen = mutableListOf<String?>()
val task = scheduler.registerTask("nullable") { a: String? -> seen += a; a }

scheduler.launch(task, null)
scheduler.launchLatest(task, null)
assertNull(scheduler.launchIfIdle(task, null)) // dropped, two jobs running
advanceUntilIdle()
assertNotNull(scheduler.launchIfIdle(task, null))
advanceUntilIdle()
assertNull(scheduler.start(task, null).argument)
assertNull(scheduler.startIfIdle(task, null)?.argument)
assertEquals(5, seen.size)
assertTrue(seen.all { it == null })
}

@Test
fun relaunchReRunsWithNullArgument() = runTest {
val scheduler = testScheduler()
var runs = 0
val task = scheduler.registerTask("nullable") { _: String? -> runs++ }

val first = scheduler.launch(task, null)
val byTask = scheduler.relaunch(task)
val byJob = scheduler.relaunch(first)
advanceUntilIdle()

assertNotEquals(JobHandle.NIL, byTask)
assertNotEquals(JobHandle.NIL, byJob)
assertEquals(3, runs)
}

@Test
fun launchDoesNotRetainOldStatesOrArguments() = runTest {
val scheduler = testScheduler()
val task = scheduler.registerTask("echo") { s: String -> s }

val handles = (1..50).map { scheduler.launch(task, "arg$it") }
advanceUntilIdle()

assertEquals(1, scheduler.taskJobState.size)
assertEquals(1, scheduler.finishedTaskState.size)
assertEquals(scheduler.finishedTaskState.getValue(task.id).jobId, scheduler.taskJobState.keys.single())
// the argument lives only in the handle, relaunch by an old handle still works
val again = scheduler.relaunch(handles.first())
advanceUntilIdle()
assertEquals("arg1", scheduler.taskJobState.getValue(again.id).result)
}

// endregion
Expand Down
Loading