Skip to content

Commit

Permalink
Add KotlinX interopt module for Arrow Fx Coroutines (#257)
Browse files Browse the repository at this point in the history
Co-authored-by: Rachel M. Carmena <rachelcarmena@users.noreply.github.com>
Co-authored-by: Raúl Raja Martínez <raulraja@gmail.com>
Co-authored-by: danieh <daniel.montoya@47deg.com>
Co-authored-by: Alberto Ballano <aballano@users.noreply.github.com>
  • Loading branch information
5 people authored Sep 3, 2020
1 parent 00a886f commit 6f508f8
Show file tree
Hide file tree
Showing 12 changed files with 593 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
---
layout: docs-fx
title: kotlinx.coroutines
permalink: /integrations/kotlinxcoroutines/
---

# Kotlin Coroutines and runtime support

Kotlin offers a `suspend` system in the language, and it offers intrinsics in the standard library to build a library on top. These `intrinsic` functions allow you to `startCoroutine`s, `suspendCoroutine`s, build `CoroutineContext`s and so on.

Kotlin's language suspension support can be found in the [kotlin.coroutines](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/index.html) package.

There are currently two libraries that provide a runtime for the language's suspension system.

- [Arrow Fx](https://arrow-kt.io/docs/fx/)
- [KotlinX Coroutines](https://github.com/Kotlin/kotlinx.coroutines)

They can easily interop with each other, and Arrow Fx's integration module offers certain combinators to use Arrow Fx's with KotlinX structured concurrency in frameworks that have chosen to incorporate the KotlinX Coroutines library such as Android and Ktor.

## Integrating Arrow Fx Coroutine with KotlinX Coroutine

If you'd like to introduce Arrow Fx Coroutine in your project, you might want to keep using the KotlinX Coroutines style of cancellation with `CoroutineScope`. This is especially useful on *Android* projects where the Architecture Components [already provide handy scopes for you](https://developer.android.com/topic/libraries/architecture/coroutines#lifecycle-aware).

### unsafeRunScoped & unsafeRunIO

`scope.unsafeRunScoped(f, cb)` runs the specific Arrow Fx Coroutine program with a [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html), so it will be automatically cancelled when the scope does as well.

Similarly, there's `f.unsafeRunIO(scope, cb)`, which works in the same way with different syntax:

```kotlin:ank:playground
import arrow.fx.coroutines.*
import arrow.fx.coroutines.kotlinx.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
val scope = CoroutineScope(SupervisorJob())
//sampleStart
suspend fun sayHello(): Unit =
println("Hello World")
suspend fun sayGoodBye(): Unit =
println("Good bye World!")
suspend fun greet(): Unit {
cancelBoundary()
sayHello()
cancelBoundary()
sayGoodBye()
}
fun main() {
// This Arrow Fx Coroutine program would stop as soon as the scope is cancelled
scope.unsafeRunScoped({ greet() }) { }
// alternatively, you could also do
suspend { greet() }.unsafeRunIO(scope) { }
}
//sampleEnd
```


## Alternatively, integrating Arrow Fx Coroutines with kotlinx.coroutines

Sometimes you might not want to switch the runtime of your project, and slowly integrate to Arrow Fx Coroutines instead. For this use case, we've added some extensions to work with the KotlinX Coroutines runtime.

*IMPORTANT NOTE*: The way kotlinx.coroutines handle errors is by throwing exceptions after you run your operations. Because of this, it's important to clarify that your operation might crash your app if you're not handling errors or try-catching the execution.

### suspendCancellable

The `suspendCancellable` function will turn an Arrow Fx Coroutine program into a KotlinX Coroutine, allowing you to cancel it within its scope like any other KotlinX Coroutine.

```kotlin:ank:playground
import arrow.fx.coroutines.*
import arrow.fx.coroutines.kotlinx.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.SupervisorJob
val scope = CoroutineScope(SupervisorJob())
//sampleStart
suspend fun sayHello(): Unit =
println("Hello World")
suspend fun sayGoodBye(): Unit =
println("Good bye World!")
suspend fun greet(): Unit {
cancelBoundary()
sayHello()
cancelBoundary()
sayGoodBye()
}
fun main() {
// This Arrow Fx Coroutine program would stop as soon as the scope is cancelled
scope.launch {
suspendCancellable { greet() }
}
}
//sampleEnd
```

# Handling errors

Let's briefly expand our previous example by adding a function that theoretically fetches (from network/db) the name of a person by their id:

```kotlin:ank
suspend fun fetchNameOrThrow(id: Int): String =
"fetched name for $id"
suspend fun sayHello(): Unit =
println("Hello ${fetchNameOrThrow(userId)}")
suspend fun sayGoodBye(): Unit =
println("Good bye ${fetchNameOrThrow(userId)}!")
```

Because we're using a suspend function, we know that this operation will either give us the name or throw an exception, which could cause our app to crash.

But luckily, we're able to solve this for both combinators presented above using `Either.catch`:

```kotlin:ank:playground
import arrow.core.*
import arrow.fx.coroutines.*
import arrow.fx.coroutines.kotlinx.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.SupervisorJob
val scope = CoroutineScope(SupervisorJob())
class NameNotFoundException(val id: Int): Exception("Name not found for id $id")
val userId = 1
//sampleStart
suspend fun fetchNameOrThrow(id: Int): String =
throw NameNotFoundException(id)
suspend fun sayHello(): Unit =
println("Hello ${fetchNameOrThrow(userId)}")
suspend fun sayGoodBye(): Unit =
println("Good bye ${fetchNameOrThrow(userId)}!")
fun greet(): Unit = Either.catch {
cancelBoundary()
sayHello() // This first call will throw and the exception be captured within this IO.
cancelBoundary()
sayGoodBye() // The second op will not be executed because of the above.
}.getOrElse { println("Error printing greeting") }
fun main() {
// You can safely run greet() with unsafeRunScoped
scope.unsafeRunScoped({ greet() }) { }
// or suspendCancellable + kotlinx.
suspendCancellable { greet() }
}
//sampleEnd
```
53 changes: 53 additions & 0 deletions arrow-libs/fx/arrow-docs/docs/fx/coroutines/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
layout: docs-fx
title: "Kotlin Standard Library and Arrow Fx Coroutines"
---

# Kotlin Standard Library & Arrow Fx Coroutines

## Demystify Coroutine

Kotlin's standard library defines a `Coroutine` as an instance of a suspendable computation.

In other words, a `Coroutine` is a compiled `suspend () -> A` program wired to a `Continuation`.

Which can be created by using [`kotlin.coroutines.intrinsics.createCoroutineUnintercepted`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.intrinsics/create-coroutine-unintercepted.html).

So let's take a quick look at an example.

```kotlin:ank
import kotlin.coroutines.intrinsics.createCoroutineUnintercepted
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.resume
suspend fun one(): Int = 1
val cont: Continuation<Unit> = ::one
.createCoroutineUnintercepted(Continuation(EmptyCoroutineContext, ::println))
cont.resume(Unit)
```

As you can see here above we create a `Coroutine` using `createCoroutineUnintercepted` which returns us `Continuation<Unit>`.
Strange, you might've expected a `Coroutine` type but a `Coroutine` in the type system is represented by `Continuation<Unit>`.

This `typealias Coroutine = Contination<Unit>` will start running every time you call `resume(Unit)`, which allows you to run the suspend program as many times as you want.

## Kotlin Standard Library Coroutines

[Kotlin Std Coroutines](img/kotlin-stdlib.png)

The standard library offers a powerful set of primitives to build powerful applications on top of `Continuation`s,
together with the compiler's ability to rewrite continuation based code to a beautiful `suspend` syntax.

They can be used to implement a very wide range use-cases, and or *not* bound to asynchronous -or concurrency use-cases.

- Arrow Core, offers computational DSLs build on top of Kotlin's Coroutines `either { }`, `validated { }`, etc
- [`DeepRecursiveFunction`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-deep-recursive-function/) explained [here](https://medium.com/@elizarov/deep-recursion-with-coroutines-7c53e15993e3)
- Another well-known async/concurrency implementation beside Arrow Fx Coroutines is [KotlinX Coroutines](https://github.com/Kotlin/kotlinx.coroutines).

The above image is not exhaustive list of the primitives you can find in the standard library.
For an exhaustive list check the Kotlin Standard Library API docs:
- [`kotlin.coroutines`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/)
- [`kotlin.coroutines.intrinsics`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.intrinsics/)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 26 additions & 0 deletions arrow-libs/fx/arrow-fx-coroutines-kotlinx-coroutines/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
plugins {
id "org.jetbrains.kotlin.jvm"
id "org.jlleitschuh.gradle.ktlint"
}

apply from: "$SUB_PROJECT"
apply from: "$DOC_CREATION"

dependencies {
implementation project(':arrow-fx-coroutines')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLINX_COROUTINES_VERSION"

testImplementation "io.kotest:kotest-runner-junit5-jvm:$KOTEST_VERSION"
testImplementation "io.kotest:kotest-assertions-core-jvm:$KOTEST_VERSION"
testImplementation "io.kotest:kotest-property-jvm:$KOTEST_VERSION"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$KOTLINX_COROUTINES_VERSION"
}



compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Maven publishing configuration
POM_NAME=Arrow-Fx-Coroutines-KotlinX
POM_ARTIFACT_ID=arrow-fx-coroutines-kotlinx
POM_PACKAGING=jar
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package arrow.fx.coroutines.kotlinx

import arrow.fx.coroutines.CancelToken
import arrow.fx.coroutines.CancellableContinuation
import arrow.fx.coroutines.Fiber
import arrow.fx.coroutines.never
import arrow.fx.coroutines.startCoroutineCancellable
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.newCoroutineContext
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.EmptyCoroutineContext

/**
* Launches the source `suspend () -> A` composing cancellation with the `Structured Concurrency` of KotlinX.
*
* This will make sure that the source [f] is cancelled whenever it's [CoroutineScope] is cancelled.
*/
suspend fun <A> suspendCancellable(f: suspend () -> A): A =
suspendCancellableCoroutine { cont ->
if (cont.isActive) {
val disposable = f.startCoroutineCancellable(CancellableContinuation(cont.context, cont::resumeWith))
cont.invokeOnCancellation { disposable() }
}
}

/**
* Unsafely run [fa] and receive the values in a callback [cb] while participating in structured concurrency.
* Equivalent of [startCoroutineCancellable] but with its cancellation token wired to [CoroutineScope].
*
* @see [startCoroutineCancellable] for a version that returns the cancellation token instead.
*/
fun <A> CoroutineScope.unsafeRunScoped(fa: suspend () -> A, cb: (Result<A>) -> Unit): Unit =
fa.unsafeRunScoped(this, cb)

/**
* Unsafely run `this` and receive the values in a callback [cb] while participating in structured concurrency.
* Equivalent of [startCoroutineCancellable] but with its cancellation token wired to [CoroutineScope].
*
* @see [startCoroutineCancellable] for a version that returns the cancellation token instead.
*/
fun <A> (suspend () -> A).unsafeRunScoped(
scope: CoroutineScope,
cb: (Result<A>) -> Unit
): Unit {
val newContext = scope.newCoroutineContext(EmptyCoroutineContext)
val job = newContext[Job]

if (job == null || job.isActive) {
val disposable = startCoroutineCancellable(CancellableContinuation(newContext, cb))

job?.invokeOnCompletion { e ->
if (e is CancellationException) disposable.invoke()
else Unit
}
}
}

/**
* Launches [f] as a coroutine in a [Fiber] while participating in structured concurrency.
* This guarantees resource safety upon cancellation according to [CoroutineScope]'s lifecycle.
*
* The returned [Fiber] is automatically cancelled when [CoroutineScope] gets cancelled, or
* whenever it's [Fiber.cancel] token is invoked. Whichever comes first.
*/
suspend fun <A> ForkScoped(scope: CoroutineScope, f: suspend () -> A): Fiber<A> {
val newContext = scope.newCoroutineContext(EmptyCoroutineContext)
val job = newContext[Job]

val promise = CompletableDeferred<Result<A>>(job)

return if (job == null || job.isActive) {
val disposable = f.startCoroutineCancellable(CancellableContinuation(newContext) {
promise.complete(it)
})

job?.invokeOnCompletion { e ->
if (e is CancellationException) disposable.invoke()
else Unit
}

Fiber({ promise.await().fold({ it }) { e -> throw e } }, CancelToken { disposable.invoke() })
} else Fiber({ never<A>() }, CancelToken.unit)
}
Loading

0 comments on commit 6f508f8

Please sign in to comment.