======================== CODE SNIPPETS ======================== TITLE: Build Arrow Project DESCRIPTION: Builds all Arrow libraries and examples. This command compiles the code and runs all tests for the entire project. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_0 LANGUAGE: bash CODE: ``` ./gradlew build ``` ---------------------------------------- TITLE: Option Type KDoc Example DESCRIPTION: Demonstrates how to document the `Option` type in Arrow's KDocs. It includes a description of the type and a code example showing its usage with `Some` and `none()`, annotated for generation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_4 LANGUAGE: kotlin CODE: ``` /** * (...) * * `Option` is a container for an optional value of type `A`. If the value of type `A` is present, the `Option` is an instance of `Some`, containing the present value of type `A`. If the value is absent, the `Option` is the object `None`. * * ```kotlin * import arrow.core.Option * import arrow.core.Some * import arrow.core.none * * //sampleStart * val someValue: Option = Some("I am wrapped in something") * val emptyValue: Option = none() * //sampleEnd * fun main() { * println("value = $someValue") * println("emptyValue = $emptyValue") * } * * * * (...) */ public sealed class Option { } ``` ---------------------------------------- TITLE: Arrow Project Build and Formatting Commands DESCRIPTION: Provides essential Gradle commands for Arrow project contributors. These commands are used to regenerate code examples from documentation snippets, format code according to project standards, and build the project, including API compatibility checks. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_5 LANGUAGE: bash CODE: ``` ./gradlew knit # (Re-)generate code examples from snippets in docs ``` LANGUAGE: bash CODE: ``` ./gradlew spotlessApply # Format code ``` LANGUAGE: bash CODE: ``` ./gradlew build ``` LANGUAGE: bash CODE: ``` ./gradlew buildDoc ``` ---------------------------------------- TITLE: Generate and Validate Documentation DESCRIPTION: Generates documentation using Dokka and validates code snippets using Knit. The 'knit' task regenerates examples, and 'buildDoc' generates and validates the documentation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_2 LANGUAGE: bash CODE: ``` ./gradlew knit ``` LANGUAGE: bash CODE: ``` ./gradlew buildDoc ``` ---------------------------------------- TITLE: Knit Code Generation DESCRIPTION: Regenerates code examples from snippets embedded in KDocs using the Knit tool. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_6 LANGUAGE: bash CODE: ``` ./gradlew knit ``` ---------------------------------------- TITLE: Standard Gradle Build Tasks DESCRIPTION: Executes common build and formatting tasks for the project, including spotlessApply for code formatting, build for compiling, and buildDoc for documentation generation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_7 LANGUAGE: bash CODE: ``` ./gradlew spotlessApply ./gradlew build ./gradlew buildDoc ``` ---------------------------------------- TITLE: Gradle Dependency Configurations DESCRIPTION: Lists and describes common Gradle dependency configurations used in the Arrow project, explaining their scope and usage. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_10 LANGUAGE: APIDOC CODE: ``` Gradle dependency configurations: | Configuration | Use | Note | |----------------------|---------------------------------|---------------------------------------| | `api` | compilation | exported to consumers for compilation | | `implementation` | compilation + runtime | exported to consumers for runtime | | `compileOnly` | just compilation | not exported to consumers | | `runtimeOnly` | just runtime | exported to consumers for runtime | | `testImplementation` | test compilation + test runtime | | | `testCompileOnly` | test compilation | | | `testRuntimeOnly` | test runtime | | ``` ---------------------------------------- TITLE: Gradle Wrapper Update DESCRIPTION: Updates the Gradle wrapper to a specified version, ensuring the project uses the desired Gradle version. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_9 LANGUAGE: bash CODE: ``` ./gradlew wrapper --gradle-version ``` ---------------------------------------- TITLE: Example Usage of ContinuationInterceptor DESCRIPTION: Demonstrates how to implement and use a custom ContinuationInterceptor (Printer) to intercept and log continuation activities. It shows how to start a coroutine with the custom interceptor and analyzes the output. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_5 LANGUAGE: kotlin CODE: ``` import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.Continuation import kotlin.coroutines.ContinuationInterceptor import kotlin.coroutines.CoroutineContext import kotlin.coroutines.startCoroutine suspend fun helloWorld(): String = "Hello World!" fun main() { ::helloWorld.startCoroutine(Continuation(Printer) { println("Received result: $it") }) } object Printer : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { override fun interceptContinuation(continuation: Continuation): Continuation { val newContinuation = object : Continuation { override val context: CoroutineContext = continuation.context override fun resumeWith(result: Result) { println("PrinterContinuation resume: pass $result to original continuation") continuation.resumeWith(result) } } println("interceptContinuation($continuation)\nand returning a new one: $newContinuation\n") return newContinuation } override fun releaseInterceptedContinuation(continuation: Continuation<*>) { super.releaseInterceptedContinuation(continuation) println("releaseInterceptedContinuation($continuation)") } } ``` ---------------------------------------- TITLE: startCoroutine Implementation DESCRIPTION: Illustrates the internal implementation of `startCoroutine`, showing how it combines `createCoroutineUnintercepted`, `intercepted`, and `resume` to start a coroutine. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_8 LANGUAGE: kotlin CODE: ``` public fun (suspend () -> T).startCoroutine(completion: Continuation) { createCoroutineUnintercepted(completion).intercepted().resume(Unit) } ``` ---------------------------------------- TITLE: API Check and Dump DESCRIPTION: Handles API compatibility checks during the build process. If the API check fails, `apiDump` must be run to update the API definition files. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_8 LANGUAGE: bash CODE: ``` > Task :arrow-core:apiCheck FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':arrow-core:apiCheck'. > API check failed for project arrow-core. --- /Users/john/projects/arrow/arrow-libs/core/arrow-core/api/arrow-core-retrofit.api +++ /Users/john/projects/arrow/arrow-libs/core/arrow-core/build/api/arrow-core-retrofit.api To make the check pass you need to run: ```bash ./gradlew apiDump ``` ``` ---------------------------------------- TITLE: Knit Code Snippet Annotation DESCRIPTION: Demonstrates the annotation format used by Knit within KDoc comments to mark code examples for validation and generation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_3 LANGUAGE: kotlin CODE: ``` /** * ```kotlin * // Code example goes here * ``` * */ ``` ---------------------------------------- TITLE: startCoroutineUninterceptedOrReturn Usage DESCRIPTION: Demonstrates the usage of `startCoroutineUninterceptedOrReturn` with examples of immediate and suspending coroutines, highlighting the differences in return values and callback invocation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_12 LANGUAGE: kotlin CODE: ``` @SinceKotlin("1.3") public actual inline fun (suspend () -> T).startCoroutineUninterceptedOrReturn( completion: Continuation ): Any? = (this as Function1, Any?>).invoke(completion) ``` LANGUAGE: kotlin CODE: ``` import kotlin.coroutines.Continuation import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED suspend fun immediateHelloWorld(): String = suspendCoroutineUninterceptedOrReturn { cont -> "Hello World!" } suspend fun suspendingHelloWorld(): String = suspendCoroutineUninterceptedOrReturn { cont -> cont.resumeWith(Result.success("Hello World!")) COROUTINE_SUSPENDED } fun main() { ::immediateHelloWorld.startCoroutineUninterceptedOrReturn(Continuation(EmptyCoroutineContext) { println("I am never called") }).also { println("Immediately returned: $it") } ::suspendingHelloWorld.startCoroutineUninterceptedOrReturn(Continuation(EmptyCoroutineContext) { println("I am called with result: $it") }).also { println("suspending returned: $it") } } ``` ---------------------------------------- TITLE: Use Arrow Dependencies in build.gradle.kts DESCRIPTION: This snippet demonstrates how to declare Arrow dependencies in the build.gradle.kts file using the configured version catalog. It includes examples for autoclose, core, and fx.coroutines modules. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/version-catalog/README.MD#_snippet_1 LANGUAGE: gradle CODE: ``` dependencies { implementation(arrow.autoclose) implementation(arrow.core) implementation(arrow.fx.coroutines) etc } ``` ---------------------------------------- TITLE: Starting a Cancellable Coroutine DESCRIPTION: Shows how to launch a coroutine in a cancellable manner using `SuspendConnection`. It registers a `CancelToken` and starts a coroutine that sleeps for a duration. When `connection.cancel()` is called, the `CancelToken` runs, and the coroutine is cancelled before it can complete. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_16 LANGUAGE: kotlin CODE: ``` import arrow.fx.coroutines.CancelToken import arrow.fx.coroutines.SuspendConnection import arrow.fx.coroutines.seconds import arrow.fx.coroutines.sleep import kotlin.coroutines.Continuation import kotlin.coroutines.startCoroutine suspend fun main() { val connection = SuspendConnection() connection.push(CancelToken { println("CancelToken ran") }) suspend { sleep(1.seconds) }.startCoroutine(Continuation(connection) { println("This never runs, since sleep was cancelled.") }) connection.cancel() Thread.sleep(2000) // Sleep longer than suspend program } ``` ---------------------------------------- TITLE: Build Specific Arrow Module DESCRIPTION: Builds a specific module within the Arrow project, such as 'arrow-core'. It requires identifying the module name first. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_1 LANGUAGE: bash CODE: ``` ./gradlew projects ``` LANGUAGE: bash CODE: ``` ./gradlew :arrow-core:build ``` ---------------------------------------- TITLE: CoroutineContext Element Example DESCRIPTION: Demonstrates the creation of a custom CoroutineContext Element in Kotlin, showing how to define a key for type-specific instances within the context. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_0 LANGUAGE: kotlin CODE: ``` class CoroutineName(val name: String): CoroutineContext.Element { companion object Key : CoroutineContext.Key override val key: CoroutineContext.Key<*> = Key } ``` ---------------------------------------- TITLE: Formatting Code with Gradle Spotless DESCRIPTION: Runs the `spotlessApply` Gradle task to automatically format the project's source code according to predefined style guidelines. This ensures code consistency across contributions. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_11 LANGUAGE: Bash CODE: ``` ./gradlew spotlessApply ``` ---------------------------------------- TITLE: Building Project Documentation with Gradle DESCRIPTION: Runs the `buildDoc` Gradle task, which compiles and generates the project's documentation, likely using Dokka. This ensures the documentation is up-to-date. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_13 LANGUAGE: Bash CODE: ``` ./gradlew buildDoc ``` ---------------------------------------- TITLE: Building the Project with Gradle DESCRIPTION: Executes the main `build` Gradle task, which typically includes compilation, testing, and other checks like `apiCheck`. This is a fundamental step to verify the project's integrity. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_12 LANGUAGE: Bash CODE: ``` ./gradlew build ``` ---------------------------------------- TITLE: New Module Gradle Properties DESCRIPTION: This snippet shows the essential properties to include in a new module's `gradle.properties` file. These properties define the module's artifact ID, name, and packaging for Gradle and Maven. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/How-to-setup-a-new-module.md#_snippet_0 LANGUAGE: gradle CODE: ``` POM_ARTIFACT_ID=your-artifact-id POM_NAME=Your Module Name (optional) POM_PACKAGING=jar (optional) ``` ---------------------------------------- TITLE: Run Detekt DESCRIPTION: Executes the Detekt static analysis tool. It is recommended to run this before pushing code to ensure code quality standards are met. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/Useful-command-line-tips.md#_snippet_2 LANGUAGE: bash CODE: ``` ./gradlew detekt ``` ---------------------------------------- TITLE: Upgrading Gradle Wrapper DESCRIPTION: Updates the Gradle wrapper script (`gradlew`) to use a specified new version of Gradle. This command is run in the project root directory to manage the Gradle version used by the project. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_15 LANGUAGE: Bash CODE: ``` ./gradlew wrapper --gradle-version ``` ---------------------------------------- TITLE: GPG/PGP Signing Requirements DESCRIPTION: Details the environment variables required for signing artifacts with GPG/PGP, a mandatory step for publishing to Maven Central. It links to external resources for key generation and distribution. SOURCE: https://github.com/arrow-kt/arrow/blob/main/RELEASE.md#_snippet_2 LANGUAGE: markdown CODE: ``` * `ORG_GRADLE_PROJECT_SIGNINGKEY`: private key from [Generating a Key Pair](https://central.sonatype.org/publish/requirements/gpg/#generating-a-key-pair) * `ORG_GRADLE_PROJECT_SIGNINGPASSWORD`: passphrase from [Generating a Key Pair](https://central.sonatype.org/publish/requirements/gpg/#generating-a-key-pair) ``` ---------------------------------------- TITLE: Debug Tests (Show Failures) DESCRIPTION: Executes Gradle tests and displays only the tests that have failed. The '-i' flag enables informational output. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/Useful-command-line-tips.md#_snippet_0 LANGUAGE: bash CODE: ``` ./gradlew test -i ``` ---------------------------------------- TITLE: Debug Tests (Detailed JVM) DESCRIPTION: Executes Gradle tests with detailed JVM debugging information. This is useful for diagnosing issues during test execution. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/Useful-command-line-tips.md#_snippet_1 LANGUAGE: bash CODE: ``` ./gradlew test -i --debug-jvm ``` ---------------------------------------- TITLE: Dumping Public API with Gradle DESCRIPTION: Executes the `apiDump` Gradle task to generate or update the `.api` files that track the project's public API surface. This is necessary when public APIs are added or changed to pass the `apiCheck` task. SOURCE: https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#_snippet_14 LANGUAGE: Bash CODE: ``` ./gradlew apiDump ``` ---------------------------------------- TITLE: Arrow Fx STM API Documentation DESCRIPTION: Provides access to the public API documentation for Arrow Fx STM, detailing its components and usage. This includes information on the STM type and its associated operations. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-stm/README.md#_snippet_0 LANGUAGE: APIDOC CODE: ``` Arrow Fx STM API Documentation: Access the full API documentation for Arrow Fx STM at: https://arrow-kt.io/docs/next/apidocs/arrow-fx-stm/arrow.fx.stm/-s-t-m/index.html This documentation covers: - The `STM` type and its core functionalities. - Transactional operations and their semantics. - Integration with other Arrow Fx modules. ``` ---------------------------------------- TITLE: startCoroutine Function DESCRIPTION: Illustrates the usage of the startCoroutine function from Kotlin's standard library to initiate a suspendable computation. It shows how to provide a Continuation to handle the result, including success and failure cases. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_2 LANGUAGE: kotlin CODE: ``` import kotlin.coroutines.Continuation import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.startCoroutine suspend fun one(): Int = 1 suspend fun fail(): Int = TODO() fun main() { ::one.startCoroutine(Continuation(EmptyCoroutineContext) { result -> println(result) // Success(1) }) ::fail.startCoroutine(Continuation(EmptyCoroutineContext) { result -> println(result) // Failure(kotlin.NotImplementedError: An operation is not implemented.) }) } ``` ---------------------------------------- TITLE: Sonatype Nexus Publish Plugin Usage DESCRIPTION: References a Gradle plugin used for managing the closing and releasing of staging repositories on Sonatype OSS. This plugin automates parts of the release process. SOURCE: https://github.com/arrow-kt/arrow/blob/main/RELEASE.md#_snippet_1 LANGUAGE: gradle CODE: ``` apply plugin: 'io.github.gradle-nexus.publish' // Note: This plugin must be applied to the root project. ``` ---------------------------------------- TITLE: startCoroutine Implementation DESCRIPTION: Provides the internal implementation of the startCoroutine function in Kotlin, detailing its composition of createCoroutineUnintercepted, intercepted, and resume to manage suspendable computations. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_3 LANGUAGE: kotlin CODE: ``` public fun (suspend () -> T).startCoroutine(completion: Continuation) { createCoroutineUnintercepted(completion).intercepted().resume(Unit) } ``` ---------------------------------------- TITLE: Configure Arrow Version Catalog in settings.gradle.kts DESCRIPTION: This snippet shows how to configure the version catalog for Arrow Kotlin in the settings.gradle.kts file. It specifies the repository and the Arrow version catalog artifact. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/version-catalog/README.MD#_snippet_0 LANGUAGE: kotlin CODE: ``` dependencyResolutionManagement { repositories { mavenCentral() } versionCatalogs { create("arrow") { from("io.arrow-kt:arrow-version-catalog:2.1.2") } } } ``` ---------------------------------------- TITLE: Bintray Upload Command DESCRIPTION: Executes the Bintray upload task with dry run disabled. Ensure Bintray credentials are set in environment variables or project properties. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/DEPRECATED---Release-process.md#_snippet_0 LANGUAGE: gradle CODE: ``` ./gradlew bintrayUpload -PdryRun=false ``` ---------------------------------------- TITLE: Gradle Dependency Management with Arrow BOM DESCRIPTION: Demonstrates how to include the Arrow Kotlin BOM in a Gradle project to manage versions of Arrow modules like arrow-core, arrow-fx, and arrow-mtl without explicitly specifying versions for each. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/stack/README.md#_snippet_0 LANGUAGE: gradle CODE: ``` dependencies { implementation platform("io.arrow-kt:arrow-stack:$ARROW_VERSION") // Versions are no longer required here implementation "io.arrow-kt:arrow-core" implementation "io.arrow-kt:arrow-fx" implementation "io.arrow-kt:arrow-mtl" ... } ``` ---------------------------------------- TITLE: Fixing Released Versions (Branching and Versioning) DESCRIPTION: Outlines the process for creating a patch release to fix bugs in a previously released version. It involves creating a new release branch, applying fixes, and updating version properties. SOURCE: https://github.com/arrow-kt/arrow/blob/main/RELEASE.md#_snippet_3 LANGUAGE: markdown CODE: ``` 1. Create `release/` branch from tag ``. 2. Apply the fix into the new branch: * Via pull request for new changes. * Directly for existing changes (cherry-pick). 3. Check that new `` artifacts are deployed into [Sonatype OSS](https://oss.sonatype.org/service/local/repositories/snapshots/content/io/arrow-kt/) with the fixes. 4. Try the new `` version. 5. Create a pull request into `main` branch if the fix must be applied to the new versions as well. 6. Create a pull request into `release/` branch to release the fix: * Change just `projects.latestVersion` in `arrow-libs/gradle.properties`. * Update the version in `README.md`. ``` ---------------------------------------- TITLE: Update Project Versions (Gradle Properties) DESCRIPTION: Specifies how to update project versions in the `gradle.properties` file for release and snapshot builds. This is a crucial step in preparing for a new release. SOURCE: https://github.com/arrow-kt/arrow/blob/main/RELEASE.md#_snippet_0 LANGUAGE: gradle CODE: ``` projects.version=0.11.0-SNAPSHOT projects.latestVersion=0.10.5 ``` ---------------------------------------- TITLE: Arrow KT Data Type Patterns DESCRIPTION: Explains common patterns for defining data types in Arrow KT, including the use of type aliases for higher-kinded types, evidence methods for typeclass inference, data class constructors, tag types for type parameterization, companion objects for smart constructors, and instance methods for typeclass implementations. SOURCE: https://github.com/arrow-kt/arrow/blob/main/__wiki__/DEPRECATED---Creating-a-new-data-type.md#_snippet_0 LANGUAGE: APIDOC CODE: ``` Data Types in Arrow KT: 1. **Package**: Defines the package for imports. ```kotlin package kategory ``` 2. **Alias**: Type aliases for higher-kinded types (generated by @higherkind). ```kotlin // Defines the higher kind this type belongs to. typealias MyTypeKind<...> = HK_N_ // Partially applied type for typeclass instances. typealias MyTypeF<...> = HK_N - 1_ ``` 3. **Evidence**: Extension methods for typeclass inference (generated by @higherkind). ```kotlin // Brings the higher kind back into implementation. fun MyTypeKind<...>.ev(): MyType<...> = this as MyType<...> // Retrieves the value for simple wrapper types. fun MyTypeKind.value(): A = this.value ``` 4. **Constructor**: Data class for equals and hashCode, or sealed class for types like Either. ```kotlin data class MyType<...>(val ...): MyTypeKind<...> ``` 5. **Tag Type (Witness)**: Non-instantiable type used in higher kinds for inference. ```kotlin class F private constructor() ``` 6. **Companion Object**: Holds smart constructors, including reified constructors using overloaded invoke operators. ```kotlin // Example of a reified constructor using invoke operator // operator fun invoke(value: A): MyType = ... ``` 7. **Instance Methods**: Implementations of methods like `map`, `flatMap`, `fold`, etc. Can use `@deriving` for instance generation. ```kotlin // Example: map implementation // fun map(f: (A) -> B): MyType = ... ``` 8. **Global Lookup of Typeclass Instances**: Instances created with `@instance` follow naming conventions (e.g., `WriterTFunctorInstance`). ```kotlin // Example of an instance declaration // @instance // val WriterTFunctorInstance: Functor = ... ``` ``` ---------------------------------------- TITLE: Intercepting Coroutines with ForkJoinPool DESCRIPTION: Demonstrates how to create a `ContinuationInterceptor` that submits coroutine continuations to a `ForkJoinPool` for execution. This allows for custom scheduling of coroutine tasks. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_6 LANGUAGE: kotlin CODE: ``` import java.util.concurrent.ForkJoinPool import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.Continuation import kotlin.coroutines.ContinuationInterceptor import kotlin.coroutines.CoroutineContext import kotlin.coroutines.startCoroutine suspend fun helloWorld(): String = "Hello from ${Thread.currentThread().name}" object CommonPoolInterceptor : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { val pool: ForkJoinPool = ForkJoinPool() override fun interceptContinuation(continuation: Continuation): Continuation = object : Continuation { override val context: CoroutineContext = continuation.context override fun resumeWith(result: Result) { pool.execute { continuation.resumeWith(result) } } } } fun main() { ::helloWorld.startCoroutine(Continuation(CommonPoolInterceptor) { println(it) }) Thread.sleep(100) } ``` ---------------------------------------- TITLE: Immediate vs. Suspended Coroutine Returns DESCRIPTION: Demonstrates how to use suspendCoroutineUninterceptedOrReturn to either return a value immediately or suspend the coroutine and return later via a continuation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_9 LANGUAGE: kotlin CODE: ``` suspend fun immediateHelloWorld(): String = suspendCoroutineUninterceptedOrReturn { cont -> "Hello World!" } ``` LANGUAGE: kotlin CODE: ``` suspend fun suspendingHelloWorld(): String = suspendCoroutineUninterceptedOrReturn { cont -> cont.resumeWith(Result.success("Hello World!")) COROUTINE_SUSPENDED } ``` ---------------------------------------- TITLE: Creating and Resuming Coroutines Unintercepted DESCRIPTION: Shows how to use `createCoroutineUnintercepted` to create a coroutine from a suspend function and then resume it multiple times. This bypasses the usual interception mechanisms. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_7 LANGUAGE: kotlin CODE: ``` import kotlin.coroutines.intrinsics.createCoroutineUnintercepted import kotlin.coroutines.Continuation import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.resume suspend fun one(): String = "Hello World!" val cont: Continuation = ::one .createCoroutineUnintercepted(Continuation(EmptyCoroutineContext, ::println)) fun main() { cont.resume(Unit) println("Fired once") cont.resume(Unit) println("Fired Twice") cont.resume(Unit) println("Fired three times") } ``` ---------------------------------------- TITLE: Cancellable Builder Implementation DESCRIPTION: Provides the implementation of the 'cancellable' suspend function builder in Arrow Kotlin. It uses suspendCoroutine to manage the continuation and integrates with SuspendConnection for cancellation handling, returning a CancelToken. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_19 LANGUAGE: kotlin CODE: ``` suspend fun cancellable(cb: ((Result) -> Unit) -> CancelToken): A = suspendCoroutine { cont -> val conn = cont.context[SuspendConnection] ?: SuspendConnection.Uncancellable val cancellable = ForwardCancellable() conn.push(cancellable.cancel()) val token = try { cb(cont::resumeWith) } catch (throwable: Throwable) { cont.resumeWith(Result.failure(throwable.nonFatalOrThrow())) CancelToken.unit } cancellable.complete(token) } ``` ---------------------------------------- TITLE: Continuation Interface DESCRIPTION: Defines the Continuation interface in Kotlin coroutines, which represents a callback for resuming suspended computations. It includes the CoroutineContext and a resume method that accepts a Result. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_1 LANGUAGE: kotlin CODE: ``` interface Continuation { val ctx: CoroutineContext fun resume(result: Result) } ``` ---------------------------------------- TITLE: Implementing a Cancel Boundary DESCRIPTION: Demonstrates how to create a `cancelBoundary` that checks for cancellation signals within a coroutine's context. It suspends execution indefinitely if the `SuspendConnection` is marked as cancelled, otherwise it returns immediately. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_15 LANGUAGE: kotlin CODE: ``` suspend fun cancelBoundary(): Unit = suspendCoroutineUninterceptedOrReturn { cont -> if (cont.context[SuspendConnection]?.isCancelled() == true) COROUTINE_SUSPENDED else Unit } ``` ---------------------------------------- TITLE: SuspendConnection API DESCRIPTION: Provides an overview of the `SuspendConnection` class, which manages `CancelToken`s for a given `SuspendConnection`. It operates as a FIFO stack, executing registered tokens in order upon cancellation. This is crucial for managing concurrent operations and ensuring proper cleanup. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_17 LANGUAGE: APIDOC CODE: ``` SuspendConnection: __init__() Initializes a new SuspendConnection. push(token: CancelToken): Unit Registers a CancelToken to be executed when the connection is cancelled. Parameters: token: The CancelToken to register. cancel(): Unit Cancels the SuspendConnection, triggering all registered CancelTokens. isCancelled(): Boolean Checks if the SuspendConnection has been cancelled. CancelToken: (suspend () -> Unit) A function that represents a cancellable operation. It will be executed when the associated SuspendConnection is cancelled. ``` ---------------------------------------- TITLE: ContinuationInterceptor Interface Definition DESCRIPTION: Defines the ContinuationInterceptor interface, a CoroutineContext.Element that allows intercepting continuation calls. It includes methods for intercepting and releasing continuations. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_4 LANGUAGE: kotlin CODE: ``` public interface ContinuationInterceptor : CoroutineContext.Element { companion object Key : CoroutineContext.Key public fun interceptContinuation(continuation: Continuation): Continuation public fun releaseInterceptedContinuation(continuation: Continuation<*>) { /* do nothing by default */ } } ``` ---------------------------------------- TITLE: Implementing Cancellable Sleep DESCRIPTION: Demonstrates how to implement a cancellable sleep function using Arrow Kotlin's 'cancellable' builder. It schedules a task to resume the continuation after a duration and returns a CancelToken to handle cancellation. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_18 LANGUAGE: kotlin CODE: ``` internal val scheduler: ScheduledExecutorService = TODO() suspend fun sleep(duration: Duration): Unit = if (duration.amount <= 0) Unit else cancellable { resumeWith: (Result) -> Unit -> val cancelRef = scheduler.schedule( { resumeWith(Result.success(Unit)) }, duration.amount, duration.timeUnit ) CancelToken { cancelRef.cancel(false) } } ``` ---------------------------------------- TITLE: suspendCoroutine Implementation DESCRIPTION: The implementation of the `suspendCoroutine` function in Kotlin. It builds upon `suspendCoroutineUninterceptedOrReturn` and ensures the continuation is intercepted for safety, especially when dealing with different dispatchers. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_11 LANGUAGE: kotlin CODE: ``` @SinceKotlin("1.3") @InlineOnly public suspend inline fun suspendCoroutine(crossinline block: (Continuation) -> Unit): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return suspendCoroutineUninterceptedOrReturn { c: Continuation -> val safe = SafeContinuation(c.intercepted()) block(safe) safe.getOrThrow() } } ``` ---------------------------------------- TITLE: Uncancellable Implementation of SuspendConnection DESCRIPTION: Describes the `Uncancellable` implementation of `SuspendConnection`, which provides no-operation methods for cancellation and always reports as not cancelled. This effectively makes all operations uncancellable when this context is active. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_14 LANGUAGE: kotlin CODE: ``` // ... (within SuspendConnection context) // The uncancellable implementation has a no-op `cancel` method, and always returns `false` upon checking `isCancelled`. // Which subsequently means that all cancellable operations become uncancellable when run on this `CoroutineContext`. // Some optimisations could be implemented when an `uncancellable` context is detected. ``` ---------------------------------------- TITLE: SuspendConnection Sealed Class DESCRIPTION: Defines the `SuspendConnection` sealed class, which is a `CoroutineContext` element used for managing cancellation in Arrow Fx Coroutines. It includes abstract methods for cancelling operations, checking cancellation status, and pushing cancellation tokens. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_13 LANGUAGE: kotlin CODE: ``` sealed class SuspendConnection : AbstractCoroutineContextElement(SuspendConnection) { companion object Key : CoroutineContext.Key abstract suspend fun cancel(): Unit abstract fun isCancelled(): Boolean abstract fun push(token: CancelToken): Unit // ... } ``` ---------------------------------------- TITLE: COROUTINE_SUSPENDED Marker Definition DESCRIPTION: Shows the definition of the COROUTINE_SUSPENDED marker used in Kotlin coroutines to signal suspension. SOURCE: https://github.com/arrow-kt/arrow/blob/main/arrow-libs/fx/arrow-fx-coroutines/README.MD#_snippet_10 LANGUAGE: kotlin CODE: ``` val COROUTINE_SUSPENDED: Any ```