diff --git a/CHANGELOG.md b/CHANGELOG.md index e87bd19..43de9bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 6341989..82561af 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.4.0") +implementation("ru.kode:reactive-tasks:2.0.0") ``` # How to use @@ -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!") } } @@ -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. @@ -165,14 +165,14 @@ 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. @@ -180,7 +180,7 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. ## 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 | @@ -189,19 +189,19 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. | `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 { -> 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` | | `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` | @@ -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> = scheduler.successResults(fetch) - fun fetch(sort: Sort) = scheduler.start(fetch, sort) + fun fetch(sort: Sort) = scheduler.launch(fetch, sort) } ``` diff --git a/gradle.properties b/gradle.properties index 131dce6..3248f2b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -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 diff --git a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt index ba2931a..f2aa1a6 100644 --- a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt +++ b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt @@ -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( @@ -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 @@ -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 start(handle: TaskHandle, argument: A, tag: Any? = null): JobHandle { + fun launch(handle: TaskHandle, argument: A, tag: Any? = null): JobHandle { return startInternal(handle, argument, tag, cancelPrevious = false) } @@ -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 startLatest(handle: TaskHandle, argument: A, tag: Any? = null): JobHandle { + fun launchLatest(handle: TaskHandle, argument: A, tag: Any? = null): JobHandle { return startInternal(handle, argument, tag, cancelPrevious = true) } @@ -318,7 +318,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 */ - suspend fun startSuspended(handle: TaskHandle, argument: A, tag: Any? = null): JobState { + suspend fun start(handle: TaskHandle, argument: A, tag: Any? = null): JobState { val jobId = Uuid.random() argumentCache.put(jobId, argument as Any?) argumentCache.put(handle.id, argument as Any?) @@ -326,42 +326,42 @@ class Scheduler( } /** - * 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 startIfIdle(handle: TaskHandle, argument: A, tag: Any? = null): JobHandle? { + fun launchIfIdle(handle: TaskHandle, 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): JobHandle? = startIfIdle(handle, Unit) + fun launchIfIdle(handle: TaskHandle): 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 startSuspendedIfIdle(handle: TaskHandle, argument: A, tag: Any? = null): JobState? { - return if (isRunning(handle)) null else startSuspended(handle, argument, tag) + suspend fun startIfIdle(handle: TaskHandle, 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): JobState? = startSuspendedIfIdle(handle, Unit) + suspend fun startIfIdle(handle: TaskHandle): JobState? = startIfIdle(handle, Unit) /** * Calls [cancelAll] when the job of [scope] completes (normally or by cancellation), or right away if it @@ -436,8 +436,8 @@ 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() @@ -445,14 +445,14 @@ class Scheduler( /** * 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 restart(handle: TaskHandle): JobHandle { + fun relaunch(handle: TaskHandle): JobHandle { @Suppress("UNCHECKED_CAST") val arg = argumentCache[handle.id] as? A? return if (arg != null) { - start(handle, arg) + launch(handle, arg) } else { JobHandle.NIL } @@ -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 } @@ -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 { return stateChanges(handle, completeOnJobCancel, replay = Replay.None) @@ -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 { diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt index b026d93..d325c49 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -61,7 +61,7 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("t") { s: String -> s.uppercase() } val collected = collect(scheduler.observeStateChanges(task)) - val job = scheduler.start(task, "a") + val job = scheduler.launch(task, "a") advanceUntilIdle() assertEquals(listOf(RunState.Running, RunState.FinishedSuccess), collected.states.map { it.runState }) @@ -81,7 +81,7 @@ class ObserveStateChangesTest { collected.job.cancel() advanceUntilIdle() - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() assertTrue(collected.states.isEmpty()) @@ -95,7 +95,7 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } val collected = collect(scheduler.observeStateChanges(task)) - val job = scheduler.start(task, 1) + val job = scheduler.launch(task, 1) runCurrent() scheduler.cancel(job) advanceUntilIdle() @@ -113,11 +113,11 @@ class ObserveStateChangesTest { val other = scheduler.registerTask("other") { _: Int -> delay(1000) } val collected = collect(scheduler.observeStateChanges(observed)) - val otherJob = scheduler.start(other, 1) + val otherJob = scheduler.launch(other, 1) runCurrent() scheduler.cancel(otherJob) advanceUntilIdle() - scheduler.start(observed, 1) + scheduler.launch(observed, 1) advanceUntilIdle() assertNull(collected.error) @@ -130,9 +130,9 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("slow") { s: String -> delay(1000); s } val collected = collect(scheduler.observeStateChanges(task, completeOnJobCancel = false)) - scheduler.startLatest(task, "a") + scheduler.launchLatest(task, "a") runCurrent() - scheduler.startLatest(task, "b") + scheduler.launchLatest(task, "b") advanceUntilIdle() assertNull(collected.error) @@ -144,7 +144,7 @@ class ObserveStateChangesTest { fun jobStatesReplaysRunningState() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } - val job = scheduler.start(task, 1) + val job = scheduler.launch(task, 1) runCurrent() val collected = collect(scheduler.jobStates(task)) @@ -159,9 +159,9 @@ class ObserveStateChangesTest { fun jobStatesDoesNotReplayFinishedOrCancelledJobs() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() - val cancelled = scheduler.start(task, 2) + val cancelled = scheduler.launch(task, 2) runCurrent() scheduler.cancel(cancelled) advanceUntilIdle() @@ -175,9 +175,9 @@ class ObserveStateChangesTest { 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) + scheduler.launch(task, 1) advanceUntilIdle() - val cancelled = scheduler.start(task, 2) + val cancelled = scheduler.launch(task, 2) runCurrent() scheduler.cancel(cancelled) advanceUntilIdle() @@ -193,7 +193,7 @@ class ObserveStateChangesTest { runCurrent() assertEquals(listOf(1), results) - scheduler.start(task, -1) + scheduler.launch(task, -1) advanceUntilIdle() val errors = mutableListOf() backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { @@ -213,10 +213,10 @@ class ObserveStateChangesTest { backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { scheduler.errors(task).collect { errors += it } } runCurrent() - scheduler.start(task, 2) - scheduler.start(task, -1) + scheduler.launch(task, 2) + scheduler.launch(task, -1) advanceUntilIdle() - val state = scheduler.startSuspended(task, 5) + val state = scheduler.start(task, 5) val doubled: Int? = state.resultOf(task) val other = scheduler.registerTask("other") { _: Unit -> } assertFailsWith { state.resultOf(other) } @@ -238,7 +238,7 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } assertFalse(scheduler.isRunning(task)) - scheduler.start(task, 1) + scheduler.launch(task, 1) runCurrent() assertTrue(scheduler.isRunning(task)) @@ -250,9 +250,9 @@ class ObserveStateChangesTest { fun successResultsReplayDuringReRunReturnsPreviousResult() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() - scheduler.start(task, 2) + scheduler.launch(task, 2) runCurrent() val results = values(scheduler.successResults(task, replayFinished = true)) @@ -266,8 +266,8 @@ class ObserveStateChangesTest { 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) + scheduler.launch(task, 1) + scheduler.launch(task, -1) advanceUntilIdle() assertEquals(emptyList(), values(scheduler.successResults(task, replayFinished = true))) @@ -278,16 +278,16 @@ class ObserveStateChangesTest { fun finishedStatesReplaysLastFinishedDuringRunningJob() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("t") { n: Int -> delay(1000); n } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() - scheduler.start(task, 2) + scheduler.launch(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) + val cancelled = scheduler.launch(task, 3) runCurrent() scheduler.cancel(cancelled) advanceUntilIdle() @@ -299,12 +299,12 @@ class ObserveStateChangesTest { fun noReplayWhenReplayIsOff() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("t") { n: Int -> if (n < 0) error("negative") else n } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() assertTrue(collect(scheduler.finishedStates(task)).states.isEmpty()) assertEquals(emptyList(), values(scheduler.successResults(task))) - scheduler.start(task, -1) + scheduler.launch(task, -1) advanceUntilIdle() assertEquals(emptyList(), values(scheduler.errors(task))) } @@ -323,7 +323,7 @@ class ObserveStateChangesTest { val running = values(scheduler.runningStates(task)) assertEquals(listOf(false), running) - scheduler.start(task, 1) + scheduler.launch(task, 1) runCurrent() assertEquals(listOf(false, true), running) @@ -341,9 +341,9 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } val running = values(scheduler.runningStates(task)) - val first = scheduler.start(task, 1) + val first = scheduler.launch(task, 1) runCurrent() - scheduler.startLatest(task, 2) + scheduler.launchLatest(task, 2) runCurrent() assertEquals(listOf(first.id), listener.cancelled.map { it.jobId }) assertEquals(listOf(false, true), running) @@ -359,7 +359,7 @@ class ObserveStateChangesTest { val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } val running = values(scheduler.runningStates(task)) - scheduler.start(task, 1) + scheduler.launch(task, 1) runCurrent() parent.cancel() advanceUntilIdle() diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt index 75edfad..1876d3c 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt @@ -81,7 +81,7 @@ class SchedulerTest { assertNotEquals(Uuid.NIL, a.id) assertEquals("TaskHandle[name=fetch,id=${a.id}]", a.toString()) - val job = scheduler.start(a, "x") + val job = scheduler.launch(a, "x") assertEquals("JobHandle[id=${job.id}]", job.toString()) assertSame(a, job.taskHandle) } @@ -106,8 +106,8 @@ class SchedulerTest { seenDefault = currentCoroutineContext()[ContinuationInterceptor] } - scheduler.start(onCustom, Unit) - scheduler.start(onDefault, Unit) + scheduler.launch(onCustom, Unit) + scheduler.launch(onDefault, Unit) advanceUntilIdle() assertSame(custom, seenCustom) @@ -124,7 +124,7 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("len") { s: String -> delay(100); s.length } - val job = scheduler.start(task, "abc", tag = "t") + val job = scheduler.launch(task, "abc", tag = "t") advanceUntilIdle() val running = JobState(job.id, task.id, "abc", RunState.Running, tag = "t") @@ -142,7 +142,7 @@ class SchedulerTest { val boom = IllegalStateException("boom") val task = scheduler.registerTask("fail") { throw boom } - val job = scheduler.start(task, Unit) + val job = scheduler.launch(task, Unit) advanceUntilIdle() assertEquals(listOf(RunState.Running, RunState.FinishedError), listener.states.map { it.runState }) @@ -158,8 +158,8 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("slow") { _: Int -> delay(100) } - val first = scheduler.start(task, 1) - val second = scheduler.start(task, 2) + val first = scheduler.launch(task, 1) + val second = scheduler.launch(task, 2) runCurrent() assertEquals(RunState.Running, scheduler.taskJobState.getValue(first.id).runState) assertEquals(RunState.Running, scheduler.taskJobState.getValue(second.id).runState) @@ -181,7 +181,7 @@ class SchedulerTest { scheduler.addTaskStateChangeListener(listener) val task = scheduler.registerTask("named") { _: Unit -> } - scheduler.start(task, Unit) + scheduler.launch(task, Unit) advanceUntilIdle() val (id, name, error) = uncaught.errors.single() @@ -195,7 +195,7 @@ class SchedulerTest { // endregion - // region startLatest + // region launchLatest @Test fun startLatestCancelsPreviousJob() = runTest { @@ -203,9 +203,9 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("search") { q: String -> delay(1000); q } - val first = scheduler.start(task, "a") + val first = scheduler.launch(task, "a") runCurrent() - val second = scheduler.startLatest(task, "ab") + val second = scheduler.launchLatest(task, "ab") advanceUntilIdle() assertEquals( @@ -224,7 +224,7 @@ class SchedulerTest { // endregion - // region startSuspended + // region start @Test fun startSuspendedReturnsFinalState() = runTest { @@ -233,13 +233,13 @@ class SchedulerTest { val boom = IllegalArgumentException("bad") val task = scheduler.registerTask("parse") { s: String -> if (s == "bad") throw boom else s.toInt() } - val ok = scheduler.startSuspended(task, "42", tag = "t") + val ok = scheduler.start(task, "42", tag = "t") assertEquals(RunState.FinishedSuccess, ok.runState) assertEquals(42, ok.result) assertEquals("t", ok.tag) assertEquals(ok, scheduler.taskJobState[ok.jobId]) - val failed = scheduler.startSuspended(task, "bad") + val failed = scheduler.start(task, "bad") assertEquals(RunState.FinishedError, failed.runState) assertSame(boom, failed.error) @@ -258,7 +258,7 @@ class SchedulerTest { val caller = launch { try { - scheduler.startSuspended(task, Unit) + scheduler.start(task, Unit) } catch (e: CancellationException) { thrown = e throw e @@ -283,19 +283,19 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("echo") { s: String -> s } - scheduler.start(task, "a", tag = "t") - val r1 = scheduler.restart(task) + scheduler.launch(task, "a", tag = "t") + val r1 = scheduler.relaunch(task) advanceUntilIdle() assertEquals("a", scheduler.taskJobState.getValue(r1.id).result) assertNull(scheduler.taskJobState.getValue(r1.id).tag) - scheduler.startLatest(task, "b", tag = "t") - val r2 = scheduler.restart(task) + scheduler.launchLatest(task, "b", tag = "t") + val r2 = scheduler.relaunch(task) advanceUntilIdle() assertEquals("b", scheduler.taskJobState.getValue(r2.id).argument) - scheduler.startSuspended(task, "c", tag = "t") - val r3 = scheduler.restart(task) + scheduler.start(task, "c", tag = "t") + val r3 = scheduler.relaunch(task) advanceUntilIdle() assertEquals("c", scheduler.taskJobState.getValue(r3.id).argument) assertNull(scheduler.taskJobState.getValue(r3.id).tag) @@ -306,9 +306,9 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("echo") { s: String -> s } - val first = scheduler.start(task, "first") - scheduler.start(task, "second") - val restarted = scheduler.restart(first) + val first = scheduler.launch(task, "first") + scheduler.launch(task, "second") + val restarted = scheduler.relaunch(first) advanceUntilIdle() assertNotEquals(first.id, restarted.id) @@ -321,8 +321,8 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("never") { _: String -> } - assertSame(JobHandle.NIL, scheduler.restart(task)) - assertSame(JobHandle.NIL, scheduler.restart(JobHandle.NIL)) + assertSame(JobHandle.NIL, scheduler.relaunch(task)) + assertSame(JobHandle.NIL, scheduler.relaunch(JobHandle.NIL)) } @Test @@ -330,15 +330,15 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("nullable") { _: String? -> } - val started = runCatching { scheduler.start(task, null) } + 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(error) } else { - assertSame(JobHandle.NIL, scheduler.restart(task)) - assertSame(JobHandle.NIL, scheduler.restart(started.getOrThrow())) + assertSame(JobHandle.NIL, scheduler.relaunch(task)) + assertSame(JobHandle.NIL, scheduler.relaunch(started.getOrThrow())) } } @@ -353,9 +353,9 @@ class SchedulerTest { val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } val other = scheduler.registerTask("other") { _: Int -> delay(1000) } - val a = scheduler.start(task, 1) - val b = scheduler.start(task, 2) - val c = scheduler.start(other, 3) + val a = scheduler.launch(task, 1) + val b = scheduler.launch(task, 2) + val c = scheduler.launch(other, 3) runCurrent() scheduler.cancel(task) advanceUntilIdle() @@ -372,8 +372,8 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } - val a = scheduler.start(task, 1) - val b = scheduler.start(task, 2) + val a = scheduler.launch(task, 1) + val b = scheduler.launch(task, 2) runCurrent() scheduler.cancel(a) advanceUntilIdle() @@ -387,8 +387,8 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } - val a = scheduler.start(task, 1) - val b = scheduler.start(task, 2) + val a = scheduler.launch(task, 1) + val b = scheduler.launch(task, 2) runCurrent() scheduler.cancelAndJoin(task) @@ -401,8 +401,8 @@ class SchedulerTest { val scheduler = testScheduler() val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } - val a = scheduler.start(task, 1) - val b = scheduler.start(task, 2) + val a = scheduler.launch(task, 1) + val b = scheduler.launch(task, 2) runCurrent() scheduler.cancelAndJoin(a) @@ -417,7 +417,7 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } - val job = scheduler.start(task, 1) + val job = scheduler.launch(task, 1) runCurrent() parent.cancel() advanceUntilIdle() @@ -436,10 +436,10 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("t") { _: Int -> } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() scheduler.removeTaskStateChangeListener(listener) - scheduler.start(task, 2) + scheduler.launch(task, 2) advanceUntilIdle() assertEquals(listOf(1, 1), listener.states.map { it.argument }) @@ -463,7 +463,7 @@ class SchedulerTest { scheduler.addTaskStateChangeListener(bystander) val task = scheduler.registerTask("t") { _: Int -> } - scheduler.start(task, 1) + scheduler.launch(task, 1) advanceUntilIdle() assertEquals(1, selfRemoving.calls) @@ -489,7 +489,7 @@ class SchedulerTest { } } - val job = scheduler.start(task, 1) + val job = scheduler.launch(task, 1) val ticker = launchTicker() runCurrent() assertTrue(scheduler.isRunning(task)) @@ -503,7 +503,7 @@ class SchedulerTest { assertEquals(listOf(job.id), listener.cancelled.map { it.jobId }) // the scheduler is still usable: tasks start and coroutines launch again - scheduler.start(task, 2) + scheduler.launch(task, 2) launchTicker() advanceTimeBy(1_050) runCurrent() @@ -513,21 +513,21 @@ class SchedulerTest { } // endregion - // region startIfIdle, startSuspendedIfIdle, bindTo, results + // region launchIfIdle, startIfIdle, bindTo, results @Test fun startIfIdleDropsStartWhileRunning() = runTest { val scheduler = testScheduler() val task = scheduler.registerTask("t") { _: Int -> delay(100) } - val first = scheduler.startIfIdle(task, 1) - val second = scheduler.startIfIdle(task, 2) + val first = scheduler.launchIfIdle(task, 1) + val second = scheduler.launchIfIdle(task, 2) runCurrent() assertTrue(first != null) assertNull(second) advanceUntilIdle() - assertTrue(scheduler.startIfIdle(task, 3) != null) + assertTrue(scheduler.launchIfIdle(task, 3) != null) } @Test @@ -536,7 +536,7 @@ class SchedulerTest { val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) val task = scheduler.registerTask("t") { _: Unit -> } - scheduler.startIfIdle(task) + scheduler.launchIfIdle(task) advanceUntilIdle() assertEquals(Unit, listener.states.last().argument) @@ -550,7 +550,7 @@ class SchedulerTest { val task = scheduler.registerTask("t") { _: Int -> gate.await() } val started = withContext(Dispatchers.Default) { - (1..200).map { async { scheduler.startIfIdle(task, it) } }.awaitAll() + (1..200).map { async { scheduler.launchIfIdle(task, it) } }.awaitAll() } assertEquals(1, started.count { it != null }) @@ -564,13 +564,13 @@ class SchedulerTest { val task = scheduler.registerTask("t") { x: Int -> x * 2 } val slow = scheduler.registerTask("slow") { _: Int -> delay(100) } - val state = scheduler.startSuspendedIfIdle(task, 21) + val state = scheduler.startIfIdle(task, 21) assertEquals(RunState.FinishedSuccess, state?.runState) assertEquals(42, state?.resultOf(task)) - scheduler.start(slow, 1) + scheduler.launch(slow, 1) runCurrent() - assertNull(scheduler.startSuspendedIfIdle(slow, 2)) + assertNull(scheduler.startIfIdle(slow, 2)) } @Test @@ -580,7 +580,7 @@ class SchedulerTest { val bound = Job() scheduler.bindTo(CoroutineScope(bound)) - val job = scheduler.start(task, 1) + val job = scheduler.launch(task, 1) runCurrent() assertTrue(scheduler.isRunning(task)) @@ -589,7 +589,7 @@ class SchedulerTest { assertTrue(job.job.isCancelled) assertTrue(!scheduler.isRunning(task)) - assertTrue(scheduler.startIfIdle(task, 2) != null) + assertTrue(scheduler.launchIfIdle(task, 2) != null) } @Test @@ -598,8 +598,8 @@ class SchedulerTest { val boom = IllegalStateException("boom") val task = scheduler.registerTask("t") { x: Int -> if (x < 0) throw boom else x } - scheduler.startSuspended(task, 1) - scheduler.startSuspended(task, -1) + scheduler.start(task, 1) + scheduler.start(task, -1) // replayLast is true by default: only the most recent finished job is replayed val replayed = scheduler.results(task).first() @@ -608,7 +608,7 @@ class SchedulerTest { val live = mutableListOf>() val collector = launch { scheduler.results(task, replayLast = false).toList(live) } runCurrent() - scheduler.startSuspended(task, 7) + scheduler.start(task, 7) runCurrent() collector.cancel() diff --git a/sample/src/main/kotlin/ru/kode/reactivetasks/Main.kt b/sample/src/main/kotlin/ru/kode/reactivetasks/Main.kt index ac8a09f..c84fd94 100644 --- a/sample/src/main/kotlin/ru/kode/reactivetasks/Main.kt +++ b/sample/src/main/kotlin/ru/kode/reactivetasks/Main.kt @@ -39,7 +39,7 @@ fun testBasicStart(scheduler: Scheduler) { if (state.runState == RunState.FinishedError || state.runState == RunState.FinishedSuccess) { latch.countDown() if (state.argument == "user-id-2200") { - scheduler.restart(fetchHandle) + scheduler.relaunch(fetchHandle) } } } @@ -51,13 +51,13 @@ fun testBasicStart(scheduler: Scheduler) { } }) - scheduler.start(fetchHandle, "user-id-100", "my tag") - scheduler.start(fetchHandle, "user-id-2200") - scheduler.start(fetchHandle, "user-id-500") + scheduler.launch(fetchHandle, "user-id-100", "my tag") + scheduler.launch(fetchHandle, "user-id-2200") + scheduler.launch(fetchHandle, "user-id-500") val scope = CoroutineScope(Dispatchers.IO) scope.launch { - val result = scheduler.startSuspended(fetchHandle, "user-id-800") + val result = scheduler.start(fetchHandle, "user-id-800") println("received suspended result $result") latch.countDown() } @@ -99,10 +99,10 @@ fun testStartLatest(scheduler: Scheduler) { if (i != 0) { delay(30) } - scheduler.startLatest(queryHandle, "query$i") + scheduler.launchLatest(queryHandle, "query$i") } delay(300) - scheduler.startLatest(queryHandle, "final-query") + scheduler.launchLatest(queryHandle, "final-query") } latch.await() } @@ -121,7 +121,7 @@ fun testFlowAdapters(scheduler: Scheduler, observeScope: CoroutineScope) { .shareIn(observeScope, SharingStarted.Lazily) .onSubscription { println("Subscribed!") - scheduler.start(handle, "300") + scheduler.launch(handle, "300") } .collect { println("Received state $it")