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

## 2.0.0 - 2026-11-12

### Changed (breaking)

Suspending functions get the short names, non-suspending ones that return a handle are named `launch`, like
`CoroutineScope.launch`.

| 1.x | 2.0.0 |
|---|---|
| `start(handle, argument, tag)`: `JobHandle` | `launch(handle, argument, tag)` |
| `startLatest(handle, argument, tag)` | `launchLatest(handle, argument, tag)` |
| `startIfIdle(handle, argument, tag)`: `JobHandle?` | `launchIfIdle(handle, argument, tag)` |
| `restart(handle)` | `relaunch(handle)` |
| `startSuspended(handle, argument, tag)`: `JobState` | `start(handle, argument, tag)` |
| `startSuspendedIfIdle(handle, argument, tag)`: `JobState?` | `startIfIdle(handle, argument, tag)` |

Migrate in two passes: first rename `start`, `startLatest`, `startIfIdle` and `restart` to the `launch` names, then
`startSuspended*` to `start*`. In the other order, a `start` call inside a coroutine still compiles and starts
waiting for the job.

## 1.4.0 - 2026-11-11

### Added
Expand Down
54 changes: 27 additions & 27 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.4.0")
implementation("ru.kode:reactive-tasks:2.0.0")
```

# How to use
Expand Down Expand Up @@ -39,25 +39,25 @@ val searchTaskHandle = scheduler.registerTask("search", body = { query: String -
//
// Start tasks in parallel
//
val jobHandle1 = scheduler.start(fetchTaskHandle, "sample-id-001")
val jobHandle2 = scheduler.start(fetchTaskHandle, "sample-id-002")
val jobHandle3 = scheduler.start(commitChangesHandle, Changes(date = LocalDate.now()))
val jobHandle1 = scheduler.launch(fetchTaskHandle, "sample-id-001")
val jobHandle2 = scheduler.launch(fetchTaskHandle, "sample-id-002")
val jobHandle3 = scheduler.launch(commitChangesHandle, Changes(date = LocalDate.now()))

//
// Start tasks where each new start cancels previous running (like Flow.flatMapLatest() does)
//
scheduler.startLatest(searchTaskHandle, "Kaliningrad")
scheduler.startLatest(searchTaskHandle, "Moscow")
scheduler.startLatest(searchTaskHandle, "Saint-Petersburg")
scheduler.launchLatest(searchTaskHandle, "Kaliningrad")
scheduler.launchLatest(searchTaskHandle, "Moscow")
scheduler.launchLatest(searchTaskHandle, "Saint-Petersburg")

//
// Start tasks as suspend-functions in some scope
//
val mainScope = CoroutineScope(Dispatchers.Main)
mainScope.launch {
val resultState = scheduler.startSuspended(fetchTaskHandle, "sample-id-003")
val resultState = scheduler.start(fetchTaskHandle, "sample-id-003")
if (resultState.result == 3) {
scheduler.startSuspended(fetchTaskHandle, "sample-id-004")
scheduler.start(fetchTaskHandle, "sample-id-004")
println("all fetches done!")
}
}
Expand Down Expand Up @@ -139,14 +139,14 @@ scheduler.cancelAll()
// Start only if no job of the task is running, atomically (two concurrent calls start one job).
// Returns the JobHandle, or null if the call was dropped
//
scheduler.startIfIdle(fetchTaskHandle, "arg")
scheduler.startIfIdle(unitTaskHandle)
scheduler.launchIfIdle(fetchTaskHandle, "arg")
scheduler.launchIfIdle(unitTaskHandle)

//
// Same, but suspends until the started job is done and returns its JobState, null if the call was dropped.
// Does not wait for an already running job. Not atomic: startSuspended jobs are not counted by isRunning
// Does not wait for an already running job. Not atomic: suspending `start` jobs are not counted by isRunning
//
scheduler.startSuspendedIfIdle(fetchTaskHandle, "arg")
scheduler.startIfIdle(fetchTaskHandle, "arg")

//
// Cancel all jobs (cancelAll) whenever the given scope completes. The scheduler stays usable.
Expand All @@ -165,22 +165,22 @@ scheduler.results(fetchTaskHandle).collect { result -> result.onSuccess { } .onF

[remo](https://github.com/appKODE/remo) (`ru.kode:remo`, `ru.kode.android:remo`, `ReactiveModel`) is deprecated,
reactive-tasks replaces it. Both run suspend "jobs" and let you observe their state, results and errors;
reactive-tasks drops the `ReactiveModel` base class and `kotlin-result`, and adds `startLatest`, `startSuspended`,
reactive-tasks drops the `ReactiveModel` base class and `kotlin-result`, and adds `launchLatest`, `start`,
`restart` and iOS.

```kotlin
// 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.4.0")
implementation("ru.kode:reactive-tasks:2.0.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.4.0 |
| remo 1.2.0 | remo 9.0.1 | reactive-tasks 2.0.0 |
|---|---|---|
| `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 All @@ -189,19 +189,19 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle<A, R>`.
| `uncaughtExceptions: Flow<Throwable>` | 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 { -> api.fetch() }` (`Task0`) | same | `registerTask("fetch") { _: Unit -> api.fetch() }`, `launch(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` |
| `taskIn(watchContext) { }`, `WatchContext.executeInModelScope { }` | same | `registerTask` + `launch` |
| 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` |
| `fetch.start(id)`: `Job` | same | `scheduler.launch(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 | `scheduler.startIfIdle(fetch, id)`: drops the start instead of throwing; plain `start` runs jobs in parallel |
| `start(id, queueingStrategy = SkipNew)` | same | `scheduler.startIfIdle(fetch, id)` (atomic, returns `JobHandle?`, null if dropped) |
| `start(id, SkipNew / Disallow).join()` | same | `scheduler.startSuspendedIfIdle(fetch, id)`: runs and waits if idle, returns `JobState?` (null, without waiting, if a job runs) |
| 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?`) |
| `start(id, queueingStrategy = Disallow)` (default, throws if a job runs) | same | `scheduler.launchIfIdle(fetch, id)`: drops the start instead of throwing; plain `launch` runs jobs in parallel |
| `start(id, queueingStrategy = SkipNew)` | same | `scheduler.launchIfIdle(fetch, id)` (atomic, returns `JobHandle?`, null if dropped) |
| `start(id, SkipNew / Disallow).join()` | same | `scheduler.startIfIdle(fetch, id)`: runs and waits if idle, returns `JobState?` (null, without waiting, if a job runs) |
| restart a running job with a new argument | same | `scheduler.launchLatest(fetch, id)`: cancels running jobs of the task |
| re-run with the last argument | same | `scheduler.relaunch(fetch)` |
| `start(id, StartScheduled.Lazily())` | same | `flow { emit(scheduler.start(fetch, id)) }`, or `shareIn(…).onSubscription { scheduler.launch(fetch, id) }` |
| — | — | `start(fetch, id)`: suspends until done, returns `JobState` (`state.resultOf(fetch)`: `R?`) |
| `fetch.jobFlow` | same | `scheduler.jobStates(fetch)`: `Flow<JobState>` |
| `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>` |
Expand All @@ -225,6 +225,6 @@ model.fetch.start(Sort.Ascending)
class UserListModel(private val scheduler: Scheduler) {
val fetch = scheduler.registerTask("fetch") { sort: Sort -> api.fetch(sort) }
val users: Flow<List<User>> = scheduler.successResults(fetch)
fun fetch(sort: Sort) = scheduler.start(fetch, sort)
fun fetch(sort: Sort) = scheduler.launch(fetch, sort)
}
```
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.4.0
versionName=2.0.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 @@ -165,16 +165,16 @@ interface TaskStateChangeListener {
* Task scheduler is the main entry point of the task system.
*
* Register tasks with [registerTask] which returns a task handle.
* This handle can be passed to [start] or [startLatest] to start the task's body.
* This handle can be passed to [launch] or [launchLatest] to start the task's body.
* An instance of started task's body is called a "job" and is represented by the [JobHandle] which
* is returned by [start] or [startLatest].
* is returned by [launch] or [launchLatest].
*
* Tasks can also be started in a "blocking" manner by calling [startSuspended] which will execute
* Tasks can also be started in a "blocking" manner by calling [start] which will execute
* tasks body, suspend and return the result. Note that you still can observe this job's state with a
* registered [TaskStateChangeListener].
*
* Tasks and Jobs can also be restarted with corresponding [restart] functions. They will reuse the arguments
* passed to [start], see [restart] documentation for more information.
* Tasks and Jobs can also be restarted with corresponding [relaunch] functions. They will reuse the arguments
* passed to [launch], see [relaunch] documentation for more information.
*/
@OptIn(ExperimentalUuidApi::class)
class Scheduler(
Expand Down Expand Up @@ -254,7 +254,7 @@ class Scheduler(

/**
* Registers a task in this scheduler. Returns a [TaskHandle] which can be used to start
* this task with [start], [startLatest], [startSuspended].
* this task with [launch], [launchLatest], [start].
*
* @param name a descriptive task name. Usually used for debug purposes.
* @param dispatcher a dispatcher to use when running this task
Expand Down Expand Up @@ -285,7 +285,7 @@ class Scheduler(
* @param argument an argument to pass to the task's body function
* @param tag an arbitrary tag to assign to the resulting task job. It will be stored in [JobState] and can be used identify groups of task jobs when needed
*/
fun <A> start(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle {
fun <A> launch(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle {
return startInternal(handle, argument, tag, cancelPrevious = false)
}

Expand All @@ -299,7 +299,7 @@ class Scheduler(
* @param argument an argument to pass to the task's body function
* @param tag an arbitrary tag to assign to the resulting task job. It will be stored in [JobState] and can be used identify groups of task jobs when needed
*/
fun <A> startLatest(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle {
fun <A> launchLatest(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle {
return startInternal(handle, argument, tag, cancelPrevious = true)
}

Expand All @@ -318,50 +318,50 @@ class Scheduler(
* @param argument an argument to pass to the task's body function
* @param tag an arbitrary tag to assign to the resulting task job. It will be stored in [JobState] and can be used identify groups of task jobs when needed
*/
suspend fun <A, R> startSuspended(handle: TaskHandle<A, R>, argument: A, tag: Any? = null): JobState {
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?)
return executeWrappedBody(handle, jobId, argument, tag)
}

/**
* Starts a new job for [handle] unless a job started with [start], [startLatest] or [restart] is still running
* Starts a new job for [handle] unless a job started with [launch], [launchLatest] or [relaunch] is still running
* ([isRunning]), in which case the call is dropped. The check and the start are one atomic step with respect to
* other [startIfIdle] calls, so two concurrent calls start exactly one job. Calls to [start], [startLatest] and
* [restart] are not serialized with it.
* other [launchIfIdle] calls, so two concurrent calls start exactly one job. Calls to [launch], [launchLatest] and
* [relaunch] are not serialized with it.
* Replaces remo's `SkipNew` / `Disallow`.
*
* @return the started job, or null if the call was dropped
*/
fun <A> startIfIdle(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle? {
fun <A> launchIfIdle(handle: TaskHandle<A, *>, argument: A, tag: Any? = null): JobHandle? {
return synchronized(startIfIdleLock) {
if (isRunning(handle)) null else startInternal(handle, argument, tag, cancelPrevious = false)
}
}

/**
* Same as `startIfIdle(handle, Unit)`
* Same as `launchIfIdle(handle, Unit)`
*/
fun startIfIdle(handle: TaskHandle<Unit, *>): JobHandle? = startIfIdle(handle, Unit)
fun launchIfIdle(handle: TaskHandle<Unit, *>): JobHandle? = launchIfIdle(handle, Unit)

/**
* Runs [startSuspended] unless a job started with [start], [startLatest] or [restart] is still running
* Runs [start] unless a job started with [launch], [launchLatest] or [relaunch] is still running
* ([isRunning]): then the call is dropped and returns null immediately, it does not wait for the running job.
* Never throws for errors of the task body, they are returned in the [JobState].
* Unlike [startIfIdle] this is not atomic: jobs started with [startSuspended] are not counted by [isRunning], so
* Unlike [launchIfIdle] this is not atomic: jobs started with [start] are not counted by [isRunning], so
* concurrent calls can all run. Replaces remo's `start().join()` with `SkipNew` / `Disallow`.
*
* @return the state of the finished job, or null if the call was dropped
*/
suspend fun <A, R> startSuspendedIfIdle(handle: TaskHandle<A, R>, argument: A, tag: Any? = null): JobState? {
return if (isRunning(handle)) null else startSuspended(handle, argument, tag)
suspend fun <A, R> startIfIdle(handle: TaskHandle<A, R>, argument: A, tag: Any? = null): JobState? {
return if (isRunning(handle)) null else start(handle, argument, tag)
}

/**
* Same as `startSuspendedIfIdle(handle, Unit)`
* Same as `startIfIdle(handle, Unit)`
*/
suspend fun startSuspendedIfIdle(handle: TaskHandle<Unit, *>): JobState? = startSuspendedIfIdle(handle, Unit)
suspend fun startIfIdle(handle: TaskHandle<Unit, *>): JobState? = startIfIdle(handle, Unit)

/**
* Calls [cancelAll] when the job of [scope] completes (normally or by cancellation), or right away if it
Expand Down Expand Up @@ -436,23 +436,23 @@ class Scheduler(
}

/**
* Returns true if a job started with [start], [startLatest] or [restart] for [handle] is still active.
* Jobs started with [startSuspended] are not counted.
* Returns true if a job started with [launch], [launchLatest] or [relaunch] for [handle] is still active.
* Jobs started with [start] 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.
* Reuses the argument of the most recent [launch] call.
* Note that there is an overload which accepts [JobHandle] instead and it will use the argument from the particular job start.
*/
fun <A, R> restart(handle: TaskHandle<A, R>): JobHandle {
fun <A, R> relaunch(handle: TaskHandle<A, R>): JobHandle {
@Suppress("UNCHECKED_CAST")
val arg = argumentCache[handle.id] as? A?
return if (arg != null) {
start(handle, arg)
launch(handle, arg)
} else {
JobHandle.NIL
}
Expand All @@ -463,10 +463,10 @@ class Scheduler(
* Reuses the argument of the specified job [handle].
* Note that there is an overload which accepts [TaskHandle] instead and it will use the argument from the most recent task start.
*/
fun restart(handle: JobHandle): JobHandle {
fun relaunch(handle: JobHandle): JobHandle {
val arg = argumentCache[handle.id]
return if (arg != null) {
start(handle.taskHandle, arg)
launch(handle.taskHandle, arg)
} else {
JobHandle.NIL
}
Expand Down Expand Up @@ -537,7 +537,7 @@ internal fun uncaughtExceptionMessage(taskId: Uuid, taskName: String): String {
*
* @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.
* [Scheduler#launchLatest] which cancels previous jobs. Jobs of other tasks never complete the flow.
*/
fun Scheduler.observeStateChanges(handle: TaskHandle<*, *>, completeOnJobCancel: Boolean): Flow<JobState> {
return stateChanges(handle, completeOnJobCancel, replay = Replay.None)
Expand Down Expand Up @@ -581,7 +581,7 @@ fun Scheduler.finishedStates(handle: TaskHandle<*, *>, replayLast: Boolean = fal
/**
* 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.
* Jobs started with [Scheduler.start] are not counted.
*/
@OptIn(ExperimentalUuidApi::class)
fun Scheduler.runningStates(handle: TaskHandle<*, *>): Flow<Boolean> {
Expand Down
Loading
Loading