CHANGES_UP_TO_1.7.md
Channel implementation with significant performance improvements across the API (#3621).select operator implementation: faster, more lightweight, and more robust (#3020).Mutex and Semaphore now share the same underlying data structure (#3020).Dispatchers.IO is added to K/N (#3205)
newFixedThreadPool and Dispatchers.Default implementations on K/N were wholly rewritten to support graceful growth under load (#3595).kotlinx-coroutines-test rework:
timeout parameter to runTest for the whole-test timeout, 10 seconds by default (#3270). This replaces the configuration of quiescence timeouts, which is now deprecated (#3603).withTimeout exception messages indicate if the timeout used the virtual time (#3588).TestCoroutineScheduler, runTest, and TestScope API are promoted to stable (#3622).runTest now also fails if there were uncaught exceptions in coroutines not inherited from the test coroutine (#1205).kotlinx-coroutines-core and kotlinx-coroutines-jdk8 artifacts were merged into a single artifact (#3268).\b symbol and are now navigable in IDE and supplied with proper documentation (#2291).CoroutineContext.isActive returns true for contexts without any job in them (#3300).JavaFx version is updated to 17.0.2 in kotlinx-coroutines-javafx (#3671)..BroadcastChannel and all the corresponding API are deprecated (#2680).Dispatchers.Default is backed by the number of threads equal to the number of available cores (#3366).Job.parent API (#3201).TestScheduler leaked cancelled jobs (#3398).TestScope.timeSource now provides comparable time marks (#3617). Thanks @hfhbd!withTimeout handles were preserved in JS runtime (#3440).awaitFrame only awaits a single frame when used from the main looper (#3432). Thanks @pablobaxter!Class-Path attribute was removed from kotlinx-coroutines-debug.jar manifest (#3361).updateThreadContext operated on the parent context (#3411).Flow.filterIsInstance extension (#3240).Dispatchers.Default thread name prefixes are now configurable with system property (#3231).Flow.timeout operator as @FlowPreview (#2624). Thanks @pablobaxter!future builder in case of exceptions (#3475). Thanks @He-Pin!Mono.awaitSingleOrNull now waits for the onComplete signal (#3487).Channel.isClosedForSend and Channel.isClosedForReceive are promoted from experimental to delicate (#3448).EventLoop (#3547).Dispatchers.IO.limitedParallelism(valueLargerThanIOSize) no longer creates an additional wrapper (#3442). Thanks @dovchinnikov!@FlowPreview and @ExperimentalCoroutinesApi are promoted to experimental and stable respectively (#3542, #3097, #3548).Dispatchers.Default and Dispatchers.IO (#3416, #3418).suspendCancellableCoroutineReusable might have hanged (#3613).CoroutineExceptionHandler is no longer invoked in case of unprocessed future failure (#3452).withContext operator (#3592).DebugProbes (#3527).CoroutineDispatcher.asExecutor() runs tasks without dispatching if the dispatcher is unconfined (#3683). Thanks @odedniv!SharedFlow.toMutableList and SharedFlow.toSet lints are introduced (#3706).Channel.invokeOnClose is promoted to stable API (#3358).Dispatchers.Default and Dispatchers.IO during the startup phase (#3652).Dispatchers.Default (#3642).limitedParallelism to perform dispatches even after the underlying dispatcher was closed (#3672).cause was selected (#3714).cause was selected (#3714).JavaFx version is updated to 17.0.2 in kotlinx-coroutines-javafx (#3671).previous-compilation-data.bin file is removed from JAR resources (#3668).CoroutineDispatcher.asExecutor() runs tasks without dispatching if the dispatcher is unconfined (#3683). Thanks @odedniv!SharedFlow.toMutableList lint overload is undeprecated (#3706).Channel.invokeOnClose is promoted to stable API (#3358).Dispatchers.Default and Dispatchers.IO during the startup phase (#3652).Dispatchers.Default (#3642).limitedParallelism to perform dispatches even after the underlying dispatcher was closed (#3672).TestScope.runTest(Long) (#3673).Channel implementation with significant performance improvements across the API (#3621).select operator implementation: faster, more lightweight, and more robust (#3020).Mutex and Semaphore now share the same underlying data structure (#3020).Dispatchers.IO is added to K/N (#3205)
newFixedThreadPool and Dispatchers.Default implementations on K/N were wholly rewritten to support graceful growth under load (#3595).kotlinx-coroutines-test rework:
timeout parameter to runTest for the whole-test timeout, 10 seconds by default (#3270). This replaces the configuration of quiescence timeouts, which is now deprecated (#3603).withTimeout exception messages indicate if the timeout used the virtual time (#3588).TestCoroutineScheduler, runTest, and TestScope API are promoted to stable (#3622).runTest now also fails if there were uncaught exceptions in coroutines not inherited from the test coroutine (#1205).kotlinx-coroutines-core and kotlinx-coroutines-jdk8 artifacts were merged into a single artifact (#3268).\b symbol and are now navigable in IDE and supplied with proper documentation (#2291).CoroutineContext.isActive returns true for contexts without any job in them (#3300).BroadcastChannel and all the corresponding API are deprecated (#2680).Dispatchers.Default is backed by the number of threads equal to the number of available cores (#3366).Job.parent API (#3201).TestScheduler leaked cancelled jobs (#3398).TestScope.timeSource now provides comparable time marks (#3617). Thanks @hfhbd!withTimeout handles were preserved in JS runtime (#3440).awaitFrame only awaits a single frame when used from the main looper (#3432). Thanks @pablobaxter!Class-Path attribute was removed from kotlinx-coroutines-debug.jar manifest (#3361).updateThreadContext operated on the parent context (#3411).Flow.filterIsInstance extension (#3240).Dispatchers.Default thread name prefixes are now configurable with system property (#3231).Flow.timeout operator as @FlowPreview (#2624). Thanks @pablobaxter!future builder in case of exceptions (#3475). Thanks @He-Pin!Mono.awaitSingleOrNull now waits for the onComplete signal (#3487).Channel.isClosedForSend and Channel.isClosedForReceive are promoted from experimental to delicate (#3448).EventLoop (#3547).Dispatchers.IO.limitedParallelism(valueLargerThanIOSize) no longer creates an additional wrapper (#3442). Thanks @dovchinnikov!@FlowPreview and @ExperimentalCoroutinesApi are promoted to experimental and stable respectively (#3542, #3097, #3548).Dispatchers.Default and Dispatchers.IO (#3416, #3418).suspendCancellableCoroutineReusable might have hanged (#3613).CoroutineExceptionHandler is no longer invoked in case of unprocessed future failure (#3452).withContext operator (#3592).DebugProbes (#3527).TestScope.backgroundScope for launching coroutines that perform work in the background and need to be cancelled at the end of the test (#3287).kotlinx-coroutines-debug having an incorrect reference to kotlinx-coroutines-bom, which cause the builds of Maven projects using the debug module to break (#3334).Publisher.await functions in kotlinx-coroutines-reactive not ensuring that the Subscriber methods are invoked serially (#3360). Thank you, @EgorKulbachka!withTimeout on K/N with the new memory model (#3351).Throwable implementations in the core library are serializable (#3328).ThreadLocalElement not being correctly updated when the most outer suspend function was called directly without kotlinx.coroutines (#2930).runBlocking event loop, and a benign data race in Mutex (#3250, #3251).TestCoroutineContext is removed, which fixes the kotlinx-coroutines-test JPMS package being split between kotlinx-coroutines-core and kotlinx-coroutines-test (#3218).0.17.2, which includes a more efficient and robust JS IR transformer (#3255).1.6.21, Gradle version is updated to 7.4.2 (#3281). Thanks, @wojtek-kalicinski!Dispatchers.Main.
This behavior was introduced in 1.6.0 and then found inconvenient and erroneous (#3106, #3113).CopyableThreadContextElement to solve issues uncovered after the initial release (#3227).ThreadLocalElement not being properly updated in racy scenarios (#2930).CoroutineExceptionHandler that triggered ANR on some devices (#3180).CoroutineDispatcher to a Rx scheduler (#968, #548). Thanks @recheej!flow builder being retained in memory (#3197).limitedParallelism on K/N with new memory model throwing ClassCastException (#3223).CoroutineContext is added to the exception printed to the default CoroutineExceptionHandler to improve debuggability (#3153).Dispatchers.Default was significantly reduced (#3137).kotlinx-coroutines-slf4j from 1.7.25 to 1.7.32.Note that this is a full changelog relative to the 1.5.2 version. Changelog relative to 1.6.0-RC3 can be found at the end.
kotlinx-coroutines-test became a multiplatform library usable from K/JVM, K/JS, and K/N.CoroutineDispatcher.limitedParallelism that allows obtaining a view of the original dispatcher with limited parallelism (#2919).Dispatchers.IO.limitedParallelism usages ignore the bound on the parallelism level of Dispatchers.IO itself to avoid starvation (#2943).Dispatchers.shutdown method for containerized environments (#2558).newSingleThreadContext and newFixedThreadPoolContext are promoted to delicate API (#2919).future builder no longer reports unhandled exceptions into the global CoroutineExceptionHandler. Thanks @vadimsemenov! (#2774, #2791).Mutex.onLock is deprecated for removal (#2794).Dispatchers.Main is now used as the default source of time for delay and withTimeout when present(#2972).
kotlinx.coroutines.main.delay system property can be set to false.collect no longer resolves when used with a non-in-place argument of a functional type. This is a candidate for a fix, uncovered after 1.6.0, see #3107 for the additional details.kotlin.native.binary.memoryModel is enabled (#2914).CopyableThreadContextElement for mutable context elements shared among multiple coroutines. Thanks @yorickhenning! (#2893).transformWhile, awaitClose, ProducerScope, merge, runningFold, runingReduce, and scan are promoted to stable API (#2971).SharedFlow.subscriptionCount no longer conflates incoming updates and gives all subscribers a chance to observe a short-lived subscription (#2488, #2863, #2871).Flow exception transparency mechanism is improved to be more exception-friendly (#3017, #2860).flat* operators that leverage multiple coroutines is no longer propagated upstream (#2964).SharedFlow.collect now returns Nothing (#2789, #2502).DisposableHandle is now fun interface, and corresponding inline extension is removed (#2790).FlowCollector is now fun interface, and corresponding inline extension is removed (#3047).processUnhandledException (#2981).Task callbacks in kotlinx-coroutines-play-services (#2990).CoroutineExceptionHandler is loaded eagerly and does not invoke ServiceLoader on its exception-handling path (#2552).ServiceLoader optimization (#2880).SendChannel.trySendBlocking is now available on Kotlin/Native (#3064).ClassValue when available (#2997).Delay interface is deprecated (#2979).CommonPool is removed.@ExperimentalTime is no longer needed for methods that use Duration (#3041).Flow.collect couldn't be called due to the @InternalCoroutinesApi annotation (#3082)TestCoroutineScheduler now provides a TimeSource with its virtual time via the timeSource property. Thanks @hfhbd! (#3087)@ExperimentalTime is no longer needed for methods that use Duration (#3041).FlowCollector is now fun interface, and corresponding inline extension is removed (#3047).TestCoroutineScope is no longer sealed, to simplify migration from it (#3072).runTest gives more informative errors when it times out waiting for external completion (#3071).SendChannel.trySendBlocking is now available on Kotlin/Native (#3064).Dispatchers.Main was not used for delay and withTimeout (#3046).kotlinx-coroutines-test became a multiplatform library usable from K/JVM, K/JS, and K/N.CoroutineDispatcher.limitedParallelism that allows obtaining a view of the original dispatcher with limited parallelism (#2919).Dispatchers.IO.limitedParallelism usages ignore the bound on the parallelism level of Dispatchers.IO itself to avoid starvation (#2943).Dispatchers.shutdown method for containerized environments (#2558).newSingleThreadContext and newFixedThreadPoolContext are promoted to delicate API (#2919).future builder no longer reports unhandled exceptions into the global CoroutineExceptionHandler. Thanks @vadimsemenov! (#2774, #2791).Mutex.onLock is deprecated for removal (#2794).Dispatchers.Main is now used as the default source of time for delay and withTimeout when present(#2972).
kotlinx.coroutines.main.delay system property can be set to false.kotlin.native.binary.memoryModel is enabled (#2914).CopyableThreadContextElement for mutable context elements shared among multiple coroutines. Thanks @yorickhenning! (#2893).transformWhile, awaitClose, ProducerScope, merge, runningFold, runingReduce, and scan are promoted to stable API (#2971).SharedFlow.subscriptionCount no longer conflates incoming updates and gives all subscribers a chance to observe a short-lived subscription (#2488, #2863, #2871).Flow exception transparency mechanism is improved to be more exception-friendly (#3017, #2860).flat* operators that leverage multiple coroutines is no longer propagated upstream (#2964).SharedFlow.collect now returns Nothing (#2789, #2502).DisposableHandle is now fun interface, and corresponding inline extension is removed (#2790).processUnhandledException (#2981).Task callbacks in kotlinx-coroutines-play-services (#2990).CoroutineExceptionHandler is loaded eagerly and does not invoke ServiceLoader on its exception-handling path (#2552).ServiceLoader optimization (#2880).ClassValue when available (#2997).Delay interface is deprecated (#2979).CommonPool is removed.onUndeliveredElement was incorrectly called on a properly received elements on JS (#2826).Dispatchers.Default on React Native, it now fully relies on setTimeout instead of stub process.nextTick. Thanks to @Legion2 (#2843).Mutex implementation (#2581).Mutex implementation is made completely lock-free as stated (#2590).update, getAndUpdate, and updateAndGet operations of MutableStateFlow (#2720).Executor.asCoroutineDispatcher implementation improvements (#2601):
ScheduledExecutorService, then its schedule API is used for time-related coroutine operations.RemoveOnCancelPolicy is now part of the public contract.Task.asDeferred and Task.await that accept CancellationTokenSource for bidirectional cancellation (#2527).1.0.3 (#2740).CopyableThrowable is allowed to modify the exception message during stacktrace recovery (#1931).CoroutineDispatcher.releaseInterceptedContinuation is now a final method (#2785).Handler.asCoroutineDispatcher now causes the dispatched coroutines to be canceled on Dispatchers.IO (#2778).ClassCastException in releaseInterceptedContinuation and IllegalStateException from tryReleaseClaimedContinuation (#2736, #2768).CompletableFuture.asDeferred when the target future has a long chain of listeners (#2730).CoroutineDispatcher.isDispatchNeeded are now considered as fatal and are propagated to the caller (#2733).DebugProbesKt (used in the debugger implementation) are moved from debug to core module.Note that this is a full changelog relative to 1.4.3 version. Changelog relative to 1.5.0-RC can be found in the end.
offer, poll, and sendBlocking methods are deprecated, internal receiveCatching and onReceiveCatching removed, receiveOrNull and onReceiveOrNull are completely deprecated. Previously deprecated SendChannel.isFull declaration is removed. Channel operators deprecated with ERROR are now HIDDEN.receiveCatching, onReceiveCatching trySend, tryReceive, and trySendBlocking along with the new result type ChannelResult are introduced. They provide better type safety, are less error-prone, and have a consistent future-proof naming scheme. The full rationale behind this change can be found here.BroadcastChannel and ConflatedBroadcastChannel are marked as ObsoleteCoroutinesApi in the favor or SharedFlow and StateFlow. The migration scheme can be found in their documentation. These classes will be deprecated in the next major release.callbackFlow and channelFlow are promoted to stable API.kotlinx-coroutines-rx2, kotlinx-coroutines-rx3, kotlinx-coroutines-reactive, kotlinx-coroutines-reactor, and kotlinx-coroutines-jdk9 were revisited and promoted to stable (#2545).publish is no longer allowed to emit null values (#2646).awaitSingleOr* functions on Publisher type are deprecated (#2591).MaybeSource.await is deprecated in the favor of awaitSingle, additional lint functions for Mono are added in order to prevent ambiguous Publisher usages (#2628, #1587).ContextView support in kotlinx-coroutines-reactor (#2575).MaybeSource.collect and Maybe.collect properly finish when they are completed without a value (#2617).Flow.last and Flow.lastOrNull operators (#2246).Flow.runningFold operator (#2641).CoroutinesTimeout rule for JUnit5 (#2197).Job and AbstractCoroutine was reworked, resulting in smaller code size, less memory footprint, and better performance (#2513, #2512).CancellationException from Kotlin standard library is used for cancellation on Kotlin/JS and Kotlin/Native (#2638).DelicateCoroutinesApi annotation that warns users about potential target API pitfalls and suggests studying API's documentation first. The only delicate API right now is GlobalScope (#2637).1.4.3 when kotlinx-coroutines-core.jar triggered IDEA debugger failure (#2619).ChildHandlerNode with reusable continuations (#2564).emitAll called from cancelled onCompletion operator (#2700).stateIn/shareIn keep strong reference to sharing job (#2557).TimeSource to AbstractTimeSource due to import issues (#2691).watchosX64 target support for Kotlin/Native (#2524).offer, poll, and sendBlocking methods are deprecated, internal receiveCatching and onReceiveCatching removed, receiveOrNull and onReceiveOrNull are completely deprecated. Previously deprecated SendChannel.isFull declaration is removed. Channel operators deprecated with ERROR are now HIDDEN.receiveCatching, onReceiveCatching trySend, tryReceive, and trySendBlocking along with the new result type ChannelResult are introduced. They provide better type safety, are less error-prone, and have a consistent future-proof naming scheme. The full rationale behind this change can be found here.BroadcastChannel and ConflatedBroadcastChannel are marked as ObsoleteCoroutinesApi in the favor or SharedFlow and StateFlow. The migration scheme can be found in their documentation. These classes will be deprecated in the next major release.callbackFlow and channelFlow are promoted to stable API.kotlinx-coroutines-rx2, kotlinx-coroutines-rx3, kotlinx-coroutines-reactive, kotlinx-coroutines-reactor, and kotlinx-coroutines-jdk9 were revisited and promoted to stable (#2545).publish is no longer allowed to emit null values (#2646).awaitSingleOr* functions on Publisher type are deprecated (#2591).MaybeSource.await is deprecated in the favor of awaitSingle, additional lint functions for Mono are added in order to prevent ambiguous Publisher usages (#2628, #1587).ContextView support in kotlinx-coroutines-reactor (#2575).MaybeSource.collect and Maybe.collect properly finish when they are completed without a value (#2617).Flow.last and Flow.lastOrNull operators (#2246).Flow.runningFold operator (#2641).CoroutinesTimeout rule for JUnit5 (#2197).Job and AbstractCoroutine was reworked, resulting in smaller code size, less memory footprint, and better performance (#2513, #2512).CancellationException from Kotlin standard library is used for cancellation on Kotlin/JS and Kotlin/Native (#2638).DelicateCoroutineApi annotation that warns users about potential target API pitfalls and suggests studying API's documentation first. The only delicate API right now is GlobalScope (#2637).1.4.3 when kotlinx-coroutines-core.jar triggered IDEA debugger failure (#2619).ChildHandlerNode with reusable continuations (#2564).ThreadContextElement (#985)ThreadContextElements are now restored in the opposite order from update (#2195)kotlinx-coroutines-reactor to 3.4.1, thanks to @sokomishalov (#2432)callInPlace contract added to ReceiveChannel.consume (#941)CoroutineStart.UNDISPATCHED promoted to stable API (#1393)kotlinx.coroutines are now released directly to MavenCentralDispatchedCoroutine by a fieldTimeSource renamed to SchedulerTimeSource to prevent wildcard import issues (#2537)Job interface (#2423)await/asDeferred for MinimalStage implementations in jdk8 module (#2456)onUndeliveredElement wasn't called for unlimited channels (#2435)ListenableFuture.isCancelled returned from asListenableFuture could have thrown an exception, thanks to @vadimsemenov (#2421)callbackFlow and produce is properly cancelled when the channel was closed separately (#2506)StackOverflowError in Job.toString when Job is observed in its intermediate state (#2371).Dispatchers.Default and Dispatchers.IO in low-loaded mode (#2381).Channel.cancel invocations (#2384).SharingStarted is now fun interface (#2397).SharedFlow to catch programmatic errors early (#2376).CoroutineStackFrame in exception recovery that triggered failures of instrumented code (#2386).kotlinx-coroutines-javafx (#2360).This is a patch release with an important fix to the SharedFlow implementation.
StateFlow, SharedFlow and corresponding operators are promoted to stable API (#2316).Flow.debounce operator with timeout selector based on each individual element is added (#1216, thanks to @mkano9!).CoroutineContext.job extension property is introduced (#2159).Flow.combine operator is reworked:
crossinline and inline-heavy internals are removed, fixing sporadic SIGSEGV on Mediatek Android devices (#1683, #1743).Flow.zip operator performance is improved by 40%.stateIn operator propagates exception to the caller when upstream fails to produce initial value (#2329).SharedFlow with replay for subscribers working at different speed (#2325).BlockHound false-positives are correctly filtered out (#2302, #2190, #2303).Observable.asFlow is fixed (#2104, #2299, thanks to @LouisCAD and @drinkthestars).Flow operators are cancellable in non-atomic way (#1813).CoroutineDispatcher throws RejectedExecutionException, cancel current Job and schedule its execution to Dispatchers.IO (#2003).CancellableContinuation.invokeOnCancellation is invoked if the continuation was cancelled while its resume has been dispatched (#1915).Flow.singleOrNull operator is aligned with standard library and does not longer throw IllegalStateException on multiple values (#2289).SharedFlow primitive for managing hot sources of events with support of various subscription mechanisms, replay logs and buffering (#2034).Flow.shareIn and Flow.stateIn operators to transform cold instances of flow to hot SharedFlow and StateFlow respectively (#2047).onUndeliveredElement in channels (#1936).kotlinx-coroutines-core (#2046, #2266).Flow to avoid accidental capturing of outer CoroutineScope for cancellation check (#2038).Flow.firstOrNull and Flow.singleOrNull by @ansman (#2229).Publisher.awaitSingleOrDefault|Null|Else extensions by @sdeleuze (#1993).awaitCancellation top-level function by @LouisCAD (#2213)..kts by @turansky.Thank you for your contributions and participation in the Kotlin community!
CoroutineContext in Flow.asPublisher and similar reactive builders (#2155).kotlinx-coroutines-core-common and kotlinx-coroutines-core-native are removed.kotlinx-coroutines-core in commonMain source-set.Flow.transformWhile operator (#2065).scanReduce with runningReduce to be consistent with the Kotlin standard library (#2139).Flow.asPublisher (#2109).ensureActive to work in the empty context case to fix IllegalStateException when using flow from suspend fun main (#2044).AbortFlowException in the Flow.first operator to avoid erroneous NoSuchElementException (#2051).kotlinx.coroutines.android from core module (#2061 by @mkj-gram).6.3 (it only affects multiplatform artifacts in this release).Flow.cancellable() operator for cooperative cancellation (#2026).flow builder now check cancellation status and are properly cancellable (#2026).currentCoroutineContext function to use unambiguously in the contexts with CoroutineScope in receiver position (#2026).EXACTLY_ONCE contract support in coroutine builders.StateFlow, new primitive for state handling (#1973, #1816, #395). The StateFlow is designed to eventually replace ConflatedBroadcastChannel for state publication scenarios. Please, try it and share your feedback. Note, that Flow-based primitives to publish events will be added later. For events you should continue to either use BroadcastChannel(1), if you put events into the StateFlow, protect them from double-processing with flags.Flow.onEmpty operator is introduced (#1890).Flow.onCompletion, it is aligned with invokeOnCompletion now and passes CancellationException to its cause parameter (#1693).runInterruptible primitive to tie cancellation with thread interruption for blocking calls. Contributed by @jxdabc (#1947).kotlinx-coroutines-debug module (#1821, #1060).suspendCancellableCoroutine, cancellation is established before invoking passed block argument (#1671).kotlinx-coroutines-core for better integration with IDEA. It should not affect library users and all the redundant code should be properly eliminated with R8.Executor.asCoroutineDispatcher (#1992).firstOrNull operator. Contributed by @bradynpoulsen.java.time adapters for Flow operators. Contributed by @fvasco.kotlin.time.Duration support (#1402). Contributed by @fvasco.DebugProbes are ready for production installation: its performance is increased, the flag to disable creation stacktraces to reduce the footprint is introduced (#1379, #1372).kotlinx-coroutines-jdk9 with adapters for java.util.concurrent.Flow.BroadcastChannel.close properly starts lazy coroutine (#1713).kotlinx-coroutines-bom is published without Gradle metadata.awaitClose calls in callbackFlow to make it less error-prone when used with callbacks (#1762, #1770). This change makes callbackFlow different from channelFlow.ReceiveChannel.asFlow extension is introduced (#1490).flow builder (#1657).Dispatcher support in Flow reactive integrations (#1765).Subscription.request calls in Flow reactive integration (#766).ObservableValue.asFlow added to JavaFx integration module (#1695).ObservableSource.asFlow added to RxJava2 integration module (#1768).kotlinx-coroutines-core is optimized for R8, making it much smaller for Android usages (75 KB for 1.3.4 release).Dispatchers.Default is improved (#1704, #1706).CoroutineDispatcher and ExecutorCoroutineDispatcher experimental coroutine context keys are introduced (#1805).Channel operations is improved (#1565).Flow.take performance is significantly improved (#1538).Flow.merge operator (#1491).take operator (#1610).NoSuchElementException instead of UnsupportedOperationException for empty Flow in reduce operator (#1659).onCompletion now rethrows downstream exceptions on emit attempt (#1654).withContext from flow builder (#1616).DebugProbes.dumpCoroutines is optimized to be able to print the 6-digit number of coroutines (#1535).CoroutinesTimeout test rule (#1542).Job-related coroutine machinery are shortened and prettified (#1574).withTimeout is supported (#1625).String parameter constructor that is not a message (#1631).Dispatchers.Default and Dispatchers.IO rework: CPU consumption is significantly lower, predictable idle threads termination (#840, #1046, #1286).ServiceLoader for loading Dispatchers.Main (#1572, #1557, #878, #1606).yield support in immediate dispatchers (#1474).CompletableDeferred.completeWith(result: Result<T>) is introduced.CoroutineDispatcher.isDispatchNeeded is promoted to stable API (#1014).select expressions are fixed (#1411, #504).null values in ListenableFuture integration (#1510).kotlinx-coroutines-core, reduced size of minified dex when using basic functionality of kotlinx-coroutines.This is a maintenance release that does not include any new features or bug fixes.
Flow are promoted to stable API.This is a minor update with various fixes:
Note: Kotlin/Native artifacts are now published with Gradle metadata format version 1.0, so you will need Gradle version 5.3 or later to use this version of kotlinx.coroutines in your Kotlin/Native project.
This version is the first stable release with Flow API.
All Flow API not marked with @FlowPreview or @ExperimentalCoroutinesApi annotations are stable and here to stay.
Flow declarations marked with @ExperimentalCoroutinesApi have the same guarantees as regular experimental API.
Please note that API marked with @FlowPreview have weak guarantees on source, binary and semantic compatibility.
CoroutineDispatcher.asExecutor extension (#1450).select statement could report the same exception twice (#1433).flatMapMerge in a case when collected values were immediately emitted to another flow (#1440).Operators for UI programming are reworked for the sake of consistency, naming scheme for operator overloads is introduced:
combineLatest is deprecated in the favor of combine.combineTransform operator for non-trivial transformations (#1224).combine and combineTransform overloads for multiple flows (#1262).switchMap is deprecated. flatMapLatest, mapLatest and transformLatest are introduced instead (#1335).collectLatest terminal operator (#1269).Improved cancellation support in flattenMerge (#1392).
channelFlow cancellation does not leak to the parent (#1334).
Fixed flow invariant enforcement for suspend fun main (#1421).
delayEach and delayFlow are deprecated (#1429).
Integration with Reactor context
await calls into Mono/Flux builder.collect call to the Publisher.Flow.asFlux builder.ServiceLoader-code is adjusted to avoid I/O on the Main thread on newer (3.6.0+) Android toolchain.
Stacktrace recovery support for minified builds on Android (#1416).
Guava version in kotlinx-coroutines-guava updated to 28.0.
setTimeout-based JS dispatcher for platforms where process is unavailable (#1404).
Native, JS and common modules are added to kotlinx-coroutines-bom.
Fixed bug with ignored acquiredPermits in Semaphore (#1423).
Flow API is promoted to stableFlow operators: withIndex, collectIndexed, distinctUntilChanged overloadFlow operators: onStart and onCompletionReceiveChannel.consumeAsFlow and emitAll (#1340)kotlinx-coroutines-bom with Maven Bill of Materials (#1110)CoroutineScope and prohibit Job instance in their context to simplify lifecycle managementsuspend fun main (#1328)CoroutineScope.cancel extension with message (#1338)delay (#1312)Duration.ZERO is handled properly in JDK 8 extensions (#1349)Flow exception transparency concept.Flow operators: onCompletion, catch, retryWhen, launchIn. onError* operators are deprecated in favour of catch. (#1263)Publisher.asFlow is integrated with buffer operator.Publisher.openSubscription default request size is 1 instead of 0 (#1267).Flow:
Flow interfaces and operators are graduated from preview status to experimental.channelFlow and callbackFlow replacements for flowViaChannel for concurrent flows or callback-based APIs.flow prohibits emissions from non-scoped coroutines by default and recommends to use channelFlow instead to avoid most of the concurrency-related bugs.AbstractFlow is introduced for extension (e.g. for managing state) and ensures all context preservation invariants.buffer operator can be used to adjust buffer size of any buffer-dependent operator (e.g. channelFlow, flowOn and flatMapMerge).conflate operator is introduced.scan, scanReduce, first, emitAll.flowWith and flowViaChannel are deprecated.retry ignores cancellation exceptions from upstream when the flow was externally cancelled (#1122).combineLatest overloads for multiple flows (#1193).drop operator.Channels:
consumeEach is promoted to experimental API (#1080).ChannelIterator.next to improve iteration performance (#1162).produce and are no longer swallowed as cancellation exceptions in case of programmatic errors (#957, #1128).Flow.General changes:
Semaphore implementation (#1088)Dispatchers.Main is tweaked so the latest version of R8 can completely remove I/O when loading it (#1231).withContext checks cancellation status on exit to make reasoning about sequential concurrent code easier (#1177).CoroutinesTimeout.seconds (#1184).nanosleep as delay in runBlocking in K/N (#1225).Major:
kotlinx-coroutines-test: runBlockingTest, TestCoroutineScope and TestCoroutineDispatcher, contributed by Sean McQuillan (@objcode). Obsolete TestCoroutineContext from kotlinx-coroutines-core is deprecated.Job.asCompletableFuture extension in jdk8 module (#1113).Flow improvements:
flowViaChannel rework: block parameter is no longer suspending, but provides CoroutineScope receiver and allows conflated channel (#1081, #1112).switchMap, sample, debounce (#1107).consumerEach is deprecated on Publisher, ObservableSource and MaybeSource, collect extension is introduced instead (#1080).Other:
CancellableContinuation.resume with onCancelling lambda (#1044) to consistently handle closeable resources.ReceiveChannel.isEmpty is no longer deprecatedA lot of Flow improvements:
zip and combineLatest operators.flatMap, merge and concatenate are replaced with flattenConcat, flattenMerge, flatMapConcat and flatMapMerge.Note that Flow is not leaving its preview status.
This release contains major feature preview: cold streams aka Flow (#254).
Performance:
Dispatcher.Main initialization is significantly improved (#878).CoroutineTimeout rule or JUnit4 is introduced to simplify coroutines debugging (#938).CopyableThrowable interface is introduced, machinery is documented (#921, #950).Dispatchers.Unconfined, MainCoroutineDispatcher.immediate, MainScope and CoroutineScope.cancel are promoted to stable API (#972).CompletableJob is introduced (#971).ensurePresent and isPresent extensions for ThreadLocal (#1028).ensureActive extensions for CoroutineContext, CoroutineScope and Job (#963).SendChannel.isFull and ReceiveChannel.isEmpty are deprecated (#1053).withContext checks cancellation on entering (#962).invoke on CoroutineDispatcher (#428).delay and withTimeout now properly handle too large values (#428).Bug fixes:
select support in debug agent (#931).supervisorScope support in debug agent (#915).initCause does no longer trigger an internal error (#933).close in order to cleanup their resources (#939).CancellableContinuation in the final state produce IllegalStateException (#901). This change does not affect #830, races between resume and cancellation do not lead to an exceptional situation.runBlocking is integrated with Dispatchers.Unconfined by sharing an internal event loop. This change does not affect the semantics of the previously correct code but allows to mix multiple runBlocking and unconfined tasks (#860).kotlinx-coroutines-debug. Debug agent that improves coroutines stacktraces, allows to print all active coroutines and its hierarchies and can be installed as Java agent.kotlinx-coroutines-test. Allows setting arbitrary Dispatchers.Main implementation for tests (#810).kotlinx.coroutines.debug system property (#493).MainScope factory and CoroutineScope.cancel extension (#829). One line CoroutineScope integration!CancellableContinuation race between resumeWithException and cancel is addressed, exceptions during cancellation are no longer reported to exception handler (#830, #892).Dispatchers.Default now consumes much less CPU on JVM (#840).DisposableHandle (#835).JavaFx initialization bug (#816).TimeoutCancellationException is thrown by withTimeout instead of CancellationException if negative timeout is supplied (#870).Dispatchers.Default on JS.kotlinx-coroutines-guava.publisher implementation with Reactive TCK.future coroutine builders on top of AbstractCoroutine (#751).Dispatchers.Default and Dispatchers.IO.JavaFx instantiation, fixes warnings on Java 9 and build on Java 11 (#463).CancellableContinuation.resumeWithException (documentation fix, see #712).withContext, coroutineScope, supervisorScope, withTimeout and withTimeoutOrNull).ExperimentalCoroutineDispatcher (#661).ExperimentalCoroutineDispatcher could end up in inconsistent state if Thread constructor throws an exception (#748).HandlerDispatcher.scheduleResumeAfterDelay, thanks @cbeyls.yield support for Unconfined and immediate dispatchers (#737).internal.kotlin.experimental.Experimental annotation. If you are using @ExperimentalCoroutinesApi or @InternalCoroutinesApi you should explicitly opt-in, otherwise compilation warning (or error) will be produced.Unconfined dispatcher (and all dispatchers which support immediate invocation) forms event-loop on top of current thread, thus preventing all StackOverflowErrors. Unconfined dispatcher is now much safer for the general use and may leave its experimental status soon (#704).kotlinx.coroutines (#537).runBlocking (#692).ReceiveChannel.receiveOrNull is marked as obsolete and deprecated.Job.cancel(cause) and ReceiveChannel.cancel(cause) are deprecated, cancel() returns Unit (#713).Dispatchers.Main is instantiated lazily (see #658 and #665).withContext cancellation (#675).Maintenance release:
Dispatchers.Main to common dispatchers, which can be used from Android, Swing and JavaFx projects if a corresponding integration library is added to dependencies.Dispatchers.Main improvement tooling bug in Android Studio #626 is mitigated, so Android users now can safely start the migration to the latest kotlinx.coroutines version.EventLoop.close contract similar to Java Executor, so it can be safely instantiated and closed multiple times (affects only unit tests).async and async-like builders cancel parent on failure (it affects CompletableDeferred, and all reactive integration builders).awaitAll (see #552).Job() wih parent now also cancels parent on failure consistently with other scopes.Job implementations propagate failure to the parent unless it is a CancellationException.SupervisorJob() and supervisorScope { ... } are introduced, allowing for a flexible implementation of custom exception-handling policies, see a new section in the guide on supervision.awaitAll in documentation and rewrote currentScope section (see #624).Dispatchers.Default by default instead of deprecated CommonPool.
DefaultDispatcher" is used as a public name of the default impl (you'll see it thread names and in the guide).-Dkotlinx.coroutines.scheduler=off can be used to switch back to CommonPool for a time being (until deprecated CommonPool is removed).CoroutineStart.ATOMIC experimental as it covers important use-case with resource cleanup in finally block (see #627).Executor.asCoroutineDispatcher (see #629).Dispatchers.Unconfined (see #621).1.0 release:
@Deprecated API. All API marked as deprecated will be removed in 1.0 release without replacement.@ExperimentalCoroutinesApi API. This API is experimental and may change in the future, but migration mechanisms will be provided. Signature, binary compatibility and semantics can be changed.@InternalCoroutinesApi. This API is intended to be used only from within kotlinx.coroutines. It can and will be changed, broken
and removed in the future releases without any warnings and migration aids. If you find yourself using this API, it is better to report
your use-case to Github issues, so decent, stable and well-tested alternative can be provided.@ObsoleteCoroutinesApi. This API has serious known flaws and will be replaced with a better alternative in the nearest releases.CancellationException, transparent parallel decomposition and consistent view of coroutines hierarchy in terms of its state (see #220 and #585).withContext is now aligned with structured concurrency and awaits for all launched tasks, its performance is significantly improved (see #553 and #617).CompletableFuture.await and ListenableFuture.await now propagate cancellation to the future (see #611).runBlocking machinery is improved (see #589).CoroutineScope factory methods add Job if it is missing from the context to enforce structured concurrency (see #610).Handler.asCoroutineDispatcher has a name parameter for better debugging (see #615).CoroutineSchedule was closed from one of its threads (see #612).CoroutineExceptionHandler are reported by default exception handler (see #562).CoroutineName is now available from common modules (see #570).Main dispatcher is async by default which may significantly improve UI performance. Contributed by @JakeWharton (see #427).CoroutineScope.plus operator (see #559).kotlinx.coroutines concurrency model (see #410 for a full explanation of the rationale behind this change):
CoroutineScope and inherit its coroutineContext. Standalone builders are deprecated.CoroutineDispatcher.Dispatchers.Default by default if CoroutineInterceptor is not present in their context.kolinx.coroutines.withContext block argument has CoroutineScope as a receiver.currentScope and coroutineScope builders are introduced to extract and provide CoroutineScope.CoroutineScope from CoroutineContext are introduced.CoroutineScope.isActive became an extension property.CommonPool are deprecated.invokeOnCompletion(onCancelling = true).Thread.contextClassLoader is mocked (see #530).IO dispatcher silently hung (see #524 and #525) .Job.cancel resulting Boolean value changed — true means exception was handled by the job, caller shall handle otherwise.CoroutineExceptionHandler for a family of coroutines receives one aggregated exception in case of failure.handleCoroutineException contract, so custom exception handlers can't break coroutines machinery.JobCancellationException properly to provide exception transparency over whole call chain.ThreadContextElement API for custom thread-context sensitive context elements.ThreadLocal.asContextElement() extension function to convert an arbitrary thread-local into coroutine context element.MDCContext element defined in kotlinx-coroutines-slf4j integration module.ExecutorCoroutineDispatcher instead of CloseableCoroutineDispatcher (see #385).kotlinx-coroutines are now JEP 238 multi-release JAR files.
VarHandle is used for atomic operations instead of Atomic*FieldUpdater for better performance.BlockingChecker extension point to control where runBlocking can be used (see #227).
runBlocking can be used anywhere without limitations (again), but it would still cause problems if improperly used on UI thread.EventLoop pseudo-constructor (see #477, PR by @Groostav).as*Future() integration functions to catch all Throwable exceptions (see #469).runBlocking cancellation (see #501).withTimeoutOrNull (see #498).EventLoop.invokeOnTimeout in DefaultDispatcher to allow busy-wait loops inside runBlocking (see #479).kotlinx-coroutines-io module from the project, it has moved to kotlinx-io.runBlocking event loop is supported at this moment.SendChannel.invokeOnClose (see #341).close, cancel, isClosedForSend, isClosedForReceive and offer linearizable with other operations (see #359).BlockingChecker mechanism which checks current context (see #227).
runBlocking from any supported UI thread (Android, JavaFx, Swing) will result in exception.UI.immediate extension as performance-optimization to immediately execute tasks which are invoked from the UI thread (see #381).
cause exception for Job onCancelling handlers (see #436).UI on Java 9 (see #443).-Dkotlinx.coroutines.scheduler option. In this case DefaultDispatcher is set to new experimental scheduler instead of FJP-based CommonPool.openChannel().use { ... } pattern by providing deprecated extension function use on ReceiveChannel.broadcast coroutine builder (see #280):
BroadcastChannel.cancel method to drop the buffer.ReceiveChannel.broadcast() extension.CancellableContinuation is not a Job anymore (see #219):
suspendCancellableCoroutine, since all the typically used functions are still there.CancellableContinuation.invokeOnCompletion is deprecated now and its semantics had subtly changed:
invokeOnCancellation is a replacement for invokeOnCompletion to install a handler.resume which corresponds to the typical usage pattern.cont.isCancelled in a typical handler code anymore (since handler is invoked only when continuation is cancelled).CancellableContinuation implementation has simpler state machine and is implemented more efficiently.AbstractContinuation (that implements CancellableContinuation) is now consistent:
CoroutineScope.coroutineContext:
coroutineContext function from Kotlin standard library.ReceiveChannel operators implementations to guarantee closing of the source channels under all circumstances (see #279):
onCompletion parameter added to produce and all other coroutine builders.ReceiveChannel.consumes(): CompletionHandler extension function.SubscriptionReceiveChannel with ReceiveChannel (see #283, PR by @deva666).
ReceiveChannel.use extension is introduced to preserve source compatibility, but is deprecated.
consume or consumeEach extensions should be used for channels.produce(onCompletion=consumes()) { ... } pattern shall be used (see #279 above).awaitAll and joinAll for Deferred and Job lists correspondingly (see #171).CompletionException exception in CompletionStage.await slow-path to provide consistent results (see #375).ExecutorService to return CloseableCoroutineDispatcher (see #278, PR by @deva666).delay, withTimeout and onTimeout (see #310).delay:
clearTimeout on cancellation in JSDispatcher.ticker function to create "ticker channels" (see #327):
Observable.timer for coroutine channels.TestCoroutineContext (see #297, PR by @streetsofboston).
CoroutineContext.DEBUG value (see #316, PR by @dmytrodanylyk):
CoroutineContext.DEBUG_PROPERTY_NAME constant public."on", "off", "auto" values.CommonPool parallelism (see #343):
CommonPool.DEFAULT_PARALLELISM_PROPERTY_NAME constant is introduced with a value of "kotlinx.coroutines.default.parallelism".Channel.filterNot (PR by @jcornaz).toString for channels (see #185).CompletionStage to Deferred (see #262, PR by @jcornaz).CompletionStage.await and make it cancellable.produce builder to close the channel on completion instead of cancelling it, which lead to lost elements with buffered channels (see #256).ForkJoinPool if there is a SecurityManager present to work around JNLP problems (see #216, PR by @NikolayMetchev).window.addEventListener when choosing default coroutine dispatcher (see #230, PR by @ScottPierce).1.3.6.2.1.9.24.0-jre.awaitFirstOrDefault and awaitFirstOrNull extensions (see #224, PR by @konrad-kaminski).withTimeout and withTimeoutOrNull that should not use equals on result (see #212, PR by @konrad-kaminski).actor builder documentation (see #210) and fixed bugs in rendered documentation due to multiplatform.runBlocking to properly support specified dispatchers (see #209).Job implementation (it was hanging at LockFreeLinkedList.helpDelete on certain stress tests).AbstractCoroutine.onCancellation is invoked before cancellation handler that is set via invokeOnCompletion.launch handles uncaught exception before another coroutine that uses join on it resumes (see #208).AbstractCoroutine:
Job, Continuation, and CoroutineScope.onStart, onCancellation, onCompleted and onCompletedExceptionally functions.launch handles uncaught exceptions before "joining" coroutines wakeup (see #208).openSubscription extension for reactive Publisher/Observable/Flowable when used with select { ... } and added an optional request parameter to specify how many elements are requested from publisher in advance on subscription (see #197).Channel.flatMap using toChannel function to work around Android 5.0 APK install SIGSEGV (see #205).DispatchTask instance is no longer allocated).Job.cancel and CompletableDeferred.complete to support cancelling/completing states and properly wait for their children to complete on join/await (see #199).delay) which could have resulted in wrong delay time in rare circumstances.Promise.asDeferred immediately installs handlers to avoid "Unhandled promise rejection" warning.window.postMessage instead of setTimeout for coroutines inside the browser to avoid timeout throttling (see #194).Window.awaitAnimationFrame to align all animations and reduce overhead.Window.asCoroutineDispatcher() extension function.launch and async coroutine builders.Job and Deferred light-weight future with cancellation support.delay and yield top-level suspending functions.await extension for JS Promise and asPromise/asDeferred conversions.promise coroutine builder.Job() and CompletableDeferred() factories.Window.awaitAnimationFrame extension function.run is deprecated and renamed to withContext (see #134).runBlocking and EventLoop implementations optimized (see #190).filter, map, etc extensions on ReceiveChannel are introduced (see #88 by @fvasco and #69 by @konrad-kaminski).ReceiveChannel.cancel method.ReceiveChannel fully consume the original channel (cancel it when they are done) using a helper consume extension.ActorJob and ProducerJob; actor now returns SendChannel and produce returns ReceiveChannel (see #127).SendChannel.sendBlocking extension method (see #157 by @@fvasco).parent job parameter for all coroutine builders so that code with an explict parent Job is more natural.parent parameter to CompletableDeferred constructor.Job.children property.Job.cancelChildren is now an extension (member is deprecated and hidden).Job.joinChildren extension is introduced.Job.attachChild as a error-prone API.java.util.ServiceLoader to find default instances of CoroutineExceptionHandler.Thread.getUncaughtExceptionPreHandler to make sure that exceptions are logged before crash (see #148).UI.awaitFrame for animation; added sample coroutine-based animation application for Android here.delay(Long.MAX_VALUE) (see #161)DefaultDispatcher on some reactive operators (see #174 by @fvasco)actor and produce so that a cancellation of a Job cancels the underlying channel (closes and removes all the pending messages).example-context-06 (see #160)Job.start on lazy coroutine with attached invokeOnCompletion handler.runBlocking and coroutines in the guide (see #166).send/openSubscription race in ArrayBroadcastChannel.
This race lead to stalled (hanged) send/receive invocations.ArrayBroadcastChannel receive of stale elements on openSubscription.
Only elements that are sent after invocation of openSubscription are received now.context parameter to rxFlowable (see #146 by @PhilGlass).UnexpectedCoroutineException is no longer used to report those cases as is removed.run uses cancelling state & propagates exceptions when cancelled (see #147):
run is cancelled, the run invocation does not
complete immediately, but waits until the body completes.Job in newSingleThreadContext and newFixedThreadPoolContext anymore (see #149, #151):
run(ctx) where ctx comes from either newSingleThreadContext or
newFixedThreadPoolContext invocation. They both used to return a combination of dispatcher + job,
and this job was overriding the parent job, thus preventing propagation of cancellation. Not anymore.ThreadPoolDispatcher class is now public and is the result type for both functions.
It has the close method to release the thread pool.try/catch or other exception handlers.ArrayBroadcastChannel between send and openChannel invocations
(see #138).runBlocking that resulted in AssertionError.
Unfortunately, cannot write a reliable stress-test to reproduce it.DefaultDispatcher is introduced (see #136):
launch, async, produce, actor and other integration-specific coroutine builders now use
DefaultDispatcher as the default value for their context parameter.newCoroutineContext function checks if there is any
interceptor/dispatcher defined in the context and uses DefaultDispatcher if there is none.DefaultDispatcher is currently defined to be equal to CommonPool.launch { ... } code and explanation on the nature
and the need for coroutine context starts in "Coroutine context and dispatchers" section.Job.attachChild and Job.cancelChildren are introduced.Job.join now always checks cancellation status of invoker coroutine for predictable behavior when joining
failed child coroutine.Job.cancelAndJoin extension is introduced.CoroutineContext.cancel and CoroutineContext.cancelChildren extensions are introduced for convenience.withTimeout/withTimeoutOrNull blocks become proper coroutines that have CoroutineScope and wait for children, too.CancellationException (as was documented before) even when
the coroutine is cancelled with another application-specific exception.JobCancellationException is introduced as a specific subclass of CancellationException which is
used for coroutines that are cancelled without cause and to wrap application-specific exceptions.Job.getCompletionException is renamed to Job.getCancellationException and return a wrapper exception if needed.Deferred.getCompletionExceptionOrNull to get not-wrapped exception result of async task.Job & Deferred to explain parent/child relations.select expression is modularized:
SelectClause(0,1,2) interfaces are introduced, so that synchronization
constructs can define their select clauses without having to modify
the source of the SelectBuilder in kotlinx-corounes-core module.Job.onJoin, Deferred.onAwait, Mutex.onLock, SendChannel.onSend, ReceiveChannel.onReceive, etc
that were functions before are now properties returning the corresponding select clauses. Old functions
are left in bytecode for backwards compatibility on use-site, but any outside code that was implementing those
interfaces by itself must be updated.TimeoutException to TimeoutCancellationException (old name is deprecated).JavaFx context (see #108).delay in arbitrary contexts (see #133).kotlinx-coroutines-io module is introduced. It is a work-in-progress on ByteReadChannel and ByteWriteChannel
interfaces, their implementations, and related classes to enable convenient coroutine integration with various
asynchronous I/O libraries and sockets. It is currently unstable and will change in the next release.withLock and consumeEach functions are now inline suspend functions.JobSupport class implementation is optimized (one fewer field).TimeoutException is public (see #89).Mutex (courtesy of @fvasco):
holdsLock (see #92).Mutex fairness (see #90).ArrayBroadcastChannel is closed concurrently with receive (see #97).setCancellation with onDipose and
updated to Aluminium-SR3 release (courtesy of @yxf07, see #96)java.time classes (courtesy of @fvasco, see #93)CompletableDeferred is introduced as a set-once event-like communication primitive (see #70).
CompletableDeferred is an interface with private impl (courtesy of @fvasco, see #86).Deferred interface with complete and completeExceptionally functions.Job.join and Deferred.await wait until a cancelled coroutine stops execution (see #64).
Job and Deferred have a new cancelling state which they enter on invocation of cancel.Job.invokeOnCompletion has an additional overload with onCancelling: Boolean parameter to
install handlers that are fired as soon as coroutine enters cancelling state as opposed
to waiting until it completes.select implementation is refactored to decouple it from JobSupport internal class
and to optimize its state-machine.AbstractCoroutine class is refactored so that it is extended only by true coroutines,
all of which support the new cancelling state.CoroutineScope.context is renamed to coroutineContext to avoid conflicts with other usages of context
in applications (like Android context, see #75).BroadcastChannel.open is renamed to openSubscription (see #54).StackOverflowError in a convoy of Mutex.unlock invokers with Unconfined dispatcher (see #80).SecurityException when trying to use coroutines library with installed SecurityManager.withTimeoutOrNull in case with nested timeouts when coroutine was cancelled before it was
ever suspended.awaitFirst on reactive streams that would have resulted in spurious stack-traces printed
on the console when used with publishers/observables that continue to invoke onNext despite being cancelled/disposed
(which they are technically allowed to do by specification).Job, Channel, BroadcastChannel, Mutex, EventLoop, and CoroutineExceptionHandler).
Previous approach of using operator invoke on their companion objects is deprecated.toString implementations for coroutine dispatcher tasks and continuations.delay is rewritten and now shares code with EventLoopImpl that is used by
runBlocking. It internally supports non-default TimeSource so that delay-using tests can be written
with "virtual time" by replacing their time source for the duration of tests (this feature is not available
outside of the library).suspendAtomicCancellableCoroutine function is introduced for funs like
send/receive/receiveOrNull that require atomic cancellation
(they cannot be cancelled after decision was made)async/launch/actor builders can be cancelled before their execution startsCoroutineStart.ATOMIC is introduced as a start mode to specify that
coroutine cannot be cancelled before its execution startsrun function is also cancellable in the same way and accepts an optional
CoroutineStart parameter to change this default.BroadcastChannel factory function is introducedCoroutineExceptionHandler factory function is introduced by @konrad-kaminskiintegration directory is introduced for all 3rd party integration projects
ListenableFuture in the new kotlinx-coroutines-guava moduleChannel and BroadcastChannel implementation bugs related to concurrent
send/close/close of channels that lead to hanging send, offer or close operations (see #66).
Thanks to @chrisly42 and @cy6erGn0m for finding them.withTimeoutOrNull which was returning null on timeout of inner or outer withTimeout blocks (see #67).
Thanks to @gregschlom for finding the problem.Job fails to dispose a handler when it is the only handler by @uchuhimoCoroutineStart enum is introduced for launch/async/actor builders:
luanch(context, start = false) is deprecated and is replaced with
launch(context, CoroutineStart.LAZY)CoroutineStart.UNDISPATCHED is introduced to start coroutine execution immediately in the invoker thread,
so that async(context, CoroutineStart.UNDISPATCHED) is similar to the behavior of C# async.BroadcastChannel interface in kotlinx-coroutines-core module:
SendChannel interface and provides open function to create subscriptions.SubscriptionReceiveChannel interface.SubscriptionReceiveChannel interfaces are removed from reactive implementation
modules. They use an interface defined in kotlinx-coroutines-core module.ConflatedBroadcastChannel implementation is provided for state-observation-like use-cases, where a coroutine or a
regular code (in UI, for example) updates the state that subscriber coroutines shall react to.ArrayBroadcastChannel implementation is provided for event-bus-like use-cases, where a sequence of events shall
be received by multiple subscribers without any omissions.Mono and Flux.
See kotlinx-coroutines-reactor module.Completable.awaitCompleted.Maybe.withTimeoutOrNull function.onTimeout clause for select expressions.withTimeout blocks on their cancellation.withTimeout when CancellationException is suppressed inside the block.
Invocation of withTimeout now always returns the result of execution of its inner block.channel property in ActorScope is promoted to a wider Channel type, so that an actor
can have an easy access to its own inbox send channel.Mutex.withMutex to Mutex.withLock, old name is deprecated.consumeEach helper function for channels and reactive streams, Rx 1.x, and Rx 2.x.
for loop on reactive streams is deprecated.awaitFirstOrDefault extension for reactive streams, Rx 1.x, and Rx 2.x.Mutex.withMutex helper function.kotlinx-coroutines-android module has provided dependency on of Android APIs to
eliminate warnings when using it in android project.kotlinx-coroutinex-android module with Android UI context implementation.whileSelect convenience function.ConflatedChannel.toXXX conversion functions to asXXX (old names are deprecated).run is optimized with fast-path case and no longer has CoroutineScope in its block.withTimeout (removed extra dispatch).EventLoop that is used by runBlocking now implements Delay, giving more predictable test behavior.Job.Registration is renamed to DisposableHandle.EmptyRegistration is renamed to NonDisposableHandle.Job.unregisterOnCompletion is renamed to Job.disposeOnCompletion.Delay.invokeOnTimeout is introduced.withTimeout now uses Delay.invokeOnTimeout when available.rxFlowable builder for Rx 2.x.Scheduler.asCoroutineDispatcher extension for Rx 2.x.onComplete in publish, rxObservable, and rxFlowable builders.Closeable.CompletableSource.await and added test for it.rx.Completable.await due to name conflict.LinkedListChannel with unlimited buffer (offer always succeeds).onLock select clause and an optional owner parameter in all Mutex functions.selectUnbiased function.actor coroutine builder.select expression with onJoin/onAwait/onSend/onReceive clauses.Mutex is moved to kotlinx.coroutines.sync package.ClosedSendChannelException is a subclass of CancellationException now.Mutex synchronization primitive is introduced.buildChannel is renamed to produce, old name is deprecated.Job.onCompletion is renamed to Job.invokeOnCompletion, old name is deprecated.delay implementation in Swing, JavaFx, and scheduled executors is fixed to avoid an extra dispatch.CancellableContinuation.resumeUndispatched is introduced to make this efficient implementation possible.CancellationException to improve performance, plus other performance improvements.defer coroutine builder is renamed to async.lazyDefer is deprecated, async has an optional start parameter instead.LazyDeferred interface is deprecated, lazy start functionality is integrated into Job interface.launch has an optional start parameter for lazily started coroutines.Job.start and Job.isCompleted are introduced.Deferred.isCompletedExceptionally and Deferred.isCancelled are introduced.Job.getInactiveCancellationException is renamed to getCompletionException.Job.join is now a member function.JobSupport state machine is enhanced to support new (not-started-yet) state.
So, lazy coroutines do not need a separate state variable to track their started/not-started (new/active) status.Job.cancel (original cause is rethrown).Job/CancellableContinuation/Deferred in docs.Channel, SendChannel, and ReceiveChannel interfaces,
RendezvousChannel and ArrayChannel implementations, Channel() factory function and buildChannel{}
coroutines builder.Here context is renamed to Unconfined (the old name is deprecated).currentCoroutineContext and related thread-locals without replacement.
Explicitly pass coroutine context around if needed.lazyDefer(context) {...} coroutine builder and LazyDeferred interface are introduced.CoroutineDispatcher.isDispatchNeeded function
has a default implementation that returns true.NonCancellable context is introduced.CoroutineDispatcher methods now have context parameter.CancellableContinuation.isCancelledEventLoop dispatcher and made it a default for runBlocking { ... }CoroutineScope interface with isActive and context properties;
standard coroutine builders include it as receiver for convenience.Executor.toCoroutineDispatcher() extension.newCoroutineContext can be explicitly disabled with -Dkotlinx.coroutines.debug=off.kotlinx-coroutines-nio module