### Installing and Composing Resources with ResourceScope
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Demonstrates how to install resources like UserProcessor and DataSource using the install function within a ResourceScope. It shows parallel composition using parZip to start and connect resources concurrently, and how to manage their lifecycle with acquire and release functions.
```kotlin
suspend fun ResourceScope.userProcessor(): UserProcessor =
install({ UserProcessor().also { it.start() } }){ p,_ -> p.shutdown() }
suspend fun ResourceScope.dataSource(): DataSource =
install({ DataSource().also { it.connect() } }) { ds, _ -> ds.close() }
suspend fun main(): Unit = resourceScope {
val service = parZip({ userProcessor() }, { dataSource() }) { userProcessor, ds ->
Service(ds, userProcessor)
}
val data = service.processData()
println(data)
}
```
--------------------------------
### install (AcquireStep)
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource-scope/index.html
Installs a resource acquired via AcquireStep into the ResourceScope.
```APIDOC
## install (AcquireStep)
### Description
Installs a resource into the `ResourceScope`. The resource is acquired using the provided `acquire` function and released using the `release` function. The `release` function is called with an `ExitCase` indicating how the scope was exited (Completed, Cancelled, or Failure).
### Method
`open suspend fun install( acquire: suspend AcquireStep.() -> A, release: suspend (A, ExitCase) -> Unit): A`
### Parameters
* `acquire`: A suspend function that acquires the resource, potentially using `AcquireStep`.
* `release`: A suspend function that takes the acquired resource and an `ExitCase` and performs the release operation.
```
--------------------------------
### Using resourceScope for Resource Management
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/resource-scope.html
Demonstrates how to use resourceScope to acquire and release a DataSource. The resource is installed with a setup block and a release block, ensuring it's closed properly when the scope exits.
```kotlin
suspend fun main(): Unit = resourceScope {
val dataSource = install({
DataSource().also { it.connect() }
}) { ds, _ -> ds.close() }
println("Using data source: ${dataSource.users()}")
}
```
--------------------------------
### install
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines.resource.context/index.html
Installs a resource within the current ResourceScope. It takes an acquisition function and a release function that handles cleanup, considering the ExitCase.
```APIDOC
## install
### Description
Installs a resource within the current ResourceScope. It takes an acquisition function and a release function that handles cleanup, considering the ExitCase.
### Signature
```kotlin
context(resources: ResourceScope) suspend fun install(acquire: suspend () -> A, release: suspend (A, ExitCase) -> Unit): A
```
### Parameters
#### Path Parameters
- `resources` (ResourceScope) - Required - The scope in which the resource is installed.
#### Request Body
- `acquire` (suspend () -> A) - Required - A suspend function to acquire the resource.
- `release` (suspend (A, ExitCase) -> Unit) - Required - A suspend function to release the resource, taking the acquired resource and an ExitCase.
```
--------------------------------
### Install Resource with Acquire and Release
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Installs a resource by acquiring it and defining a release handler. The acquire block allocates the resource, and the release block handles its cleanup.
```kotlin
suspend fun ResourceScope.userProcessor(): UserProcessor =
install({ UserProcessor().also { it.start() } }) { processor, _ ->
processor.shutdown()
}
```
--------------------------------
### install (AutoCloseable)
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource-scope/index.html
Installs an AutoCloseable resource into the ResourceScope.
```APIDOC
## install (AutoCloseable)
### Description
Installs an `AutoCloseable` resource into the `ResourceScope`. The resource will be automatically closed when the scope is released.
### Method
`@IgnorableReturnValue open fun install(autoCloseable: A): A`
### Parameters
* `autoCloseable`: The `AutoCloseable` resource to install.
```
--------------------------------
### install
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource-scope/install.html
Installs a resource into the ResourceScope. The `acquire` suspend function is responsible for obtaining the resource, and the `release` suspend function handles its cleanup, receiving the acquired resource and an `ExitCase` indicating the scope's termination reason.
```APIDOC
## install
### Description
Installs a resource into the ResourceScope. Its release function will be called with the appropriate ExitCase if this ResourceScope finishes. It results either in ExitCase.Completed, ExitCase.Cancelled or ExitCase.Failure depending on the terminal state of Resource lambda.
### Signature
open suspend fun install( acquire: suspend AcquireStep.() -> A, release: suspend (A, ExitCase) -> Unit): A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response
- **A** (type of acquired resource) - The acquired resource.
#### Response Example
None
```
--------------------------------
### Resource.asFlow() Usage Example
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/as-flow.html
Demonstrates how to use `Resource.asFlow()` to convert a resource into a Flow. This example shows reading lines from a file and emitting them as a Flow of strings.
```kotlin
import arrow.fx.coroutines.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.nio.file.Path
import kotlin.io.path.*
@OptIn(ExperimentalCoroutinesApi::class)
fun Flow.writeAll(path: Path): Flow =
closeable { path.toFile().outputStream() }
.asFlow()
.flatMapConcat { writer -> map { writer.write(it) } }
.flowOn(Dispatchers.IO)
fun Path.readAll(): Flow = flow {
useLines { lines -> emitAll(lines.asFlow()) }
}
suspend fun main() {
Path("example.kt")
.readAll()
.collect(::println)
}
```
--------------------------------
### Lazy Resource Creation with Install
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Creates a lazy representation of a resource by wrapping the install function. This is useful when you need a resource that can be acquired on demand.
```kotlin
val userProcessor: Resource = resource {
val x: UserProcessor = install(
{ UserProcessor().also { it.start() } },
{ processor, _ -> processor.shutdown() }
)
x
}
```
--------------------------------
### start
Source: https://apidocs.arrow-kt.io/arrow-eval/arrow.eval/-eval/-flat-map/index.html
Starts the Eval computation, returning an Eval representing the initial state.
```APIDOC
## start
### Description
Initiates the `Eval` computation and returns an `Eval` representing the initial state of the computation. This is an abstract function, requiring implementation by subclasses.
### Function Signature
```kotlin
abstract fun start(): Eval
```
### Returns
- **Eval** - An `Eval` representing the initial state of the computation.
```
--------------------------------
### install
Source: https://apidocs.arrow-kt.io/arrow-autoclose/arrow/-auto-close-scope/index.html
Installs an `AutoCloseable` object into the scope, ensuring it will be closed when the scope is exited.
```APIDOC
## install
### Description
Installs an `AutoCloseable` object into the scope. The `install` function guarantees that the `close()` method of the provided `autoCloseable` will be invoked when the scope is exited, regardless of whether an exception occurred.
### Method Signature
`fun install(autoCloseable: A): A`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response
Returns the installed `autoCloseable` object of type `A`.
#### Response Example
None
```
--------------------------------
### Default HttpCircuitBreaker Configuration
Source: https://apidocs.arrow-kt.io/arrow-resilience-ktor-client/arrow.resilience.ktor.client/-http-circuit-breaker/index.html
Installs the HttpCircuitBreaker plugin with default configuration settings. This example shows how to set the reset timeout, window duration, and maximum number of failures before the circuit opens.
```kotlin
install(HttpCircuitBreaker) {
circuitBreaker(
resetTimeout = 5.seconds,
windowDuration = 5.seconds,
maxFailures = 10
)
}
```
--------------------------------
### setupModule
Source: https://apidocs.arrow-kt.io/arrow-core-jackson2/arrow.integrations.jackson.module/-non-empty-collections-module/index.html
Configures the module by calling the appropriate setup methods on the provided context.
```APIDOC
## setupModule
### Description
Configures the module.
### Function Signature
`override fun setupModule(context: Module.SetupContext)`
### Parameters
* `context` (Module.SetupContext) - The context in which the module is set up.
```
--------------------------------
### install
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines.resource.context/install.html
Acquires a resource and ensures its release upon exiting the scope, handling various exit scenarios.
```APIDOC
## install
### Description
Acquires a resource using the provided `acquire` function and guarantees its release via the `release` function when the scope is exited. The `release` function receives the acquired resource and an `ExitCase` indicating how the scope was exited (e.g., normally, by exception, or by cancellation).
### Signature
```kotlin
suspend fun install(acquire: suspend () -> A, release: suspend (A, ExitCase) -> Unit): A
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* **acquire** (suspend () -> A) - Required - A suspending function that acquires the resource of type `A`.
* **release** (suspend (A, ExitCase) -> Unit) - Required - A suspending function that releases the resource `A` given an `ExitCase`.
### Response
#### Success Response
The acquired resource of type `A`.
### Response Example
(No specific example provided in source, but would return the acquired resource)
### Error Handling
Errors during acquisition or release will propagate according to coroutine exception handling mechanisms.
```
--------------------------------
### Resource.bind(): A
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource-scope/bind.html
Composes another Resource program into this ResourceScope. All release functions installed into the Resource lambda will be installed in this ResourceScope while respecting the FIFO order.
```APIDOC
## Resource.bind(): A
### Description
Compose another Resource program into this ResourceScope. All release functions installed into the Resource lambda will be installed in this ResourceScope while respecting the FIFO order.
### Method
extension function
### Signature
open suspend fun Resource.bind(): A
```
--------------------------------
### startSuspend
Source: https://apidocs.arrow-kt.io/arrow-eval/arrow.eval/-eval/-flat-map/index.html
Starts the Eval computation asynchronously, returning an Eval representing the initial state.
```APIDOC
## startSuspend
### Description
Initiates the `Eval` computation asynchronously and returns an `Eval` representing the initial state of the computation. This is an abstract function, requiring implementation by subclasses.
### Function Signature
```kotlin
open suspend override fun startSuspend(): Eval
```
### Returns
- **Eval** - An `Eval` representing the initial state of the computation.
```
--------------------------------
### startSuspend
Source: https://apidocs.arrow-kt.io/arrow-eval/arrow.eval/-suspend-eval/-flat-map/index.html
Abstract method to start the SuspendEval with a given state. This is a suspending function.
```APIDOC
## startSuspend
### Description
Abstract method to start the SuspendEval with a given state. This is a suspending function.
### Signature
```kotlin
abstract suspend override fun startSuspend(): SuspendEval
```
### Returns
- `SuspendEval` - The initial SuspendEval with the given state.
```
--------------------------------
### TMVar.tryPut Example
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-s-t-m/try-put.html
Demonstrates the usage of tryPut on a TMVar. This function returns immediately with a boolean indicating success or failure.
```kotlin
import arrow.fx.stm.TMVar
import arrow.fx.stm.atomically
suspend fun main() {
//sampleStart
val tmvar = TMVar.new(20)
val result = atomically {
tmvar.tryPut(30)
}
//sampleEnd
println("Result $result")
println("New value ${atomically { tmvar.tryTake() } }")
}
```
--------------------------------
### TQueue tryRead Example
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-s-t-m/try-read.html
Demonstrates how to use tryRead on a TQueue. This will return null if the TQueue is empty and never retries.
```kotlin
import arrow.fx.stm.TQueue
import arrow.fx.stm.atomically
suspend fun main() {
//sampleStart
val tq = TQueue.new()
val result = atomically {
tq.tryRead()
}
//sampleEnd
println("Result $result")
println("Items in queue ${atomically { tq.flush() }}")
}
```
--------------------------------
### File Copying Function with AutoCloseScope Receiver
Source: https://apidocs.arrow-kt.io/arrow-autoclose/arrow/auto-close-scope.html
This example defines a function that uses AutoCloseScope as its receiver, allowing it to directly install and manage closeable resources like Scanner and Printer.
```kotlin
fun AutoCloseScope.copyFiles(input: String, output: String) {
val scanner = install(Scanner(input))
val printer = install(Printer(output))
for(line in scanner) {
printer.print(line)
}
}
```
--------------------------------
### get
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get the focus of a POptional.
```APIDOC
abstract fun get(source: S): A
```
--------------------------------
### get Function
Source: https://apidocs.arrow-kt.io/arrow-atomic/arrow.atomic/-atomic-boolean/index.html
Gets the current value.
```APIDOC
## Function get
### Description
Gets the current value.
### Returns
The current boolean value.
```
--------------------------------
### server (port, host, watchPaths, preWait, grace, timeout, module)
Source: https://apidocs.arrow-kt.io/suspendapp-ktor/arrow.continuations.ktor/server.html
Configures and starts a Ktor ApplicationEngine as a resource. It supports graceful shutdown by allowing a grace period for in-flight requests.
```APIDOC
## server (port, host, watchPaths, preWait, grace, timeout, module)
### Description
Configures and starts a Ktor ApplicationEngine as a resource. It supports graceful shutdown by allowing a grace period for in-flight requests.
### Method
`suspend fun ResourceScope.server(
factory: ApplicationEngineFactory,
port: Int = 80,
host: String = "0.0.0.0",
watchPaths: List = listOf(WORKING_DIRECTORY_PATH),
preWait: Duration = 30.seconds,
grace: Duration = 500.milliseconds,
timeout: Duration = 500.milliseconds,
module: Application.() -> Unit = {}
): EmbeddedServer
```
--------------------------------
### get (List Index)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get an element from a List by index.
```APIDOC
operator fun PLens, List>.get(i: Int): POptional
```
--------------------------------
### server (factory, rootConfig, configure, preWait, grace, timeout)
Source: https://apidocs.arrow-kt.io/suspendapp-ktor/arrow.continuations.ktor/server.html
Configures and starts a Ktor ApplicationEngine as a resource using a ServerConfig. It emphasizes graceful shutdown with configurable preWait, grace, and timeout durations.
```APIDOC
## server (factory, rootConfig, configure, preWait, grace, timeout)
### Description
Configures and starts a Ktor ApplicationEngine as a resource using a ServerConfig. It emphasizes graceful shutdown with configurable preWait, grace, and timeout durations.
### Method
`suspend fun ResourceScope.server(
factory: ApplicationEngineFactory,
rootConfig: ServerConfig,
configure: TConfiguration.() -> Unit = {},
preWait: Duration = 30.seconds,
grace: Duration = 500.milliseconds,
timeout: Duration = 500.milliseconds
): EmbeddedServer
```
--------------------------------
### first
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-optional/index.html
Create a product of the POptional and a type C.
```APIDOC
## first
### Description
Create a product of the POptional and a type C.
### Method
open fun first(): POptional, Pair, Pair, Pair>
### Parameters
None
```
--------------------------------
### Deconstructing Resource with allocate()
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/allocate.html
Demonstrates how to use the `allocate` function to acquire a resource and its corresponding release handler. The example shows the manual invocation of the release handler in both success and exceptional cases.
```kotlin
import arrow.fx.coroutines.*
import arrow.fx.coroutines.ExitCase.Companion.ExitCase
val resource =
resource({ "Acquire" }) { _, exitCase -> println("Release $exitCase") }
@OptIn(kotlinx.coroutines.DelicateCoroutinesApi::class)
suspend fun main(): Unit {
val (acquired: String, release: suspend (ExitCase) -> Unit) = resource.allocate()
try {
/** Do something with A */
release(ExitCase.Completed)
} catch(e: Throwable) {
release(ExitCase(e))
}
}
```
--------------------------------
### Create and Run STM Block
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/stm.html
Demonstrates how to create an STM block using the `stm` helper and run it transactionally with `atomically`. It shows the use of `retry()` and `orElse` for conditional execution.
```kotlin
import arrow.fx.stm.atomically
import arrow.fx.stm.stm
suspend fun main() {
//sampleStart
val i = 4
val result = atomically {
stm {
if (i == 4) retry()
"Not 4"
} orElse { "4" }
}
//sampleEnd
println("Result $result")
}
```
--------------------------------
### getAll
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-traversal/index.html
Gets all targets of the Traversal.
```APIDOC
## getAll
### Description
Get all targets of the Traversal.
### Signature
`open fun getAll(source: S): List`
```
--------------------------------
### getAll
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get all targets of the Traversal.
```APIDOC
open fun getAll(source: S): List
```
--------------------------------
### first
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Create a product of the PLens and a type C.
```APIDOC
open override fun first(): PLens, Pair, Pair, Pair>
```
--------------------------------
### Platform.name
Source: https://apidocs.arrow-kt.io/arrow-platform/arrow.platform/-platform/index.html
Gets the name of the enum constant.
```APIDOC
expect val name: String
```
--------------------------------
### run
Source: https://apidocs.arrow-kt.io/arrow-eval/arrow.eval/-suspend-eval/-at-most-once/index.html
Executes the `AtMostOnce` computation.
```APIDOC
## run
### Description
Executes the suspend function wrapped by `AtMostOnce`. If this is the first time `run` is called, the suspend function `f` will be invoked. Subsequent calls to `run` will return the cached result without re-executing `f`.
### Signature
```kotlin
open suspend override fun run(): A
```
### Returns
The result of the suspend function `f`.
```
--------------------------------
### getOrNull
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get the focus of an Optional or `null` if the is not there.
```APIDOC
open fun getOrNull(source: S): A?
```
--------------------------------
### prepare
Source: https://apidocs.arrow-kt.io/arrow-resilience-ktor-client/arrow.resilience.ktor.client/-http-circuit-breaker/-plugin/prepare.html
Configures the HttpCircuitBreaker with a given block.
```APIDOC
## prepare
### Description
Configures the HttpCircuitBreaker with a given block.
### Signature
```kotlin
open override fun prepare( block: HttpCircuitBreaker.Configuration.() -> Unit): HttpCircuitBreaker
```
### Parameters
#### block
- `HttpCircuitBreaker.Configuration.() -> Unit` - A lambda with receiver for configuring the circuit breaker.
```
--------------------------------
### Using bracketCase for Resource Management
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/bracket-case.html
Demonstrates how to use bracketCase to acquire a file resource, read its content, and ensure the file is closed properly regardless of how the operation terminates. It shows how to handle different ExitCase scenarios during the release phase.
```kotlin
import arrow.fx.coroutines.*
class File(val url: String) {
fun open(): File = this
fun close(): Unit {}
}
suspend fun File.content(): String =
"This file contains some interesting content from $url!"
suspend fun openFile(uri: String): File = File(uri).open()
suspend fun closeFile(file: File): Unit = file.close()
suspend fun main(): Unit {
//sampleStart
val res = bracketCase(
acquire = { openFile("data.json") },
use = { file -> file.content() },
release = { file, exitCase ->
when (exitCase) {
is ExitCase.Completed -> println("File closed with $exitCase")
is ExitCase.Cancelled -> println("Program cancelled with $exitCase")
is ExitCase.Failure -> println("Program failed with $exitCase")
}
closeFile(file)
}
)
//sampleEnd
println(res)
}
```
--------------------------------
### firstOrNull
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get the first target or null.
```APIDOC
open fun firstOrNull(source: S): A?
```
--------------------------------
### Create and Acquire Permits with TSemaphore
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-t-semaphore/index.html
Demonstrates creating a TSemaphore with an initial value and acquiring one or multiple permits within an atomic transaction. The transaction will retry if permits are insufficient.
```kotlin
import arrow.fx.stm.TSemaphore
import arrow.fx.stm.atomically
suspend fun main() {
//sampleStart
val tsem = TSemaphore.new(5)
atomically {
// acquire one permit
tsem.acquire()
// acquire 3 permits
tsem.acquire(3)
}
//sampleEnd
println("Permits remaining ${atomically { tsem.available() }}")
}
```
--------------------------------
### Platform.ordinal
Source: https://apidocs.arrow-kt.io/arrow-platform/arrow.platform/-platform/index.html
Gets the declaration order of the enum constant.
```APIDOC
expect val ordinal: Int
```
--------------------------------
### Flow parMap Example
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/par-map.html
Demonstrates parallel mapping on a Flow. The `delay` simulates an I/O operation. Results are collected into a list, preserving the original order.
```kotlin
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.flow.collect
import arrow.fx.coroutines.parMap
@OptIn(kotlinx.coroutines.FlowPreview::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
//sampleStart
suspend fun main(): Unit {
flowOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.parMap { a ->
delay(100)
a
}.toList() // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
//sampleEnd
```
--------------------------------
### getNullValue Function
Source: https://apidocs.arrow-kt.io/arrow-core-jackson2/arrow.integrations.jackson.module/-non-empty-collection-deserializer/index.html
Gets the null value for the deserializer.
```APIDOC
## getNullValue Function
### Description
Gets the null value for the deserializer.
### Signature
open fun getNullValue(ctxt: DeserializationContext?): T?
```
--------------------------------
### Example of Exception-Throwing Functions
Source: https://apidocs.arrow-kt.io/arrow-core/arrow.core/-either/index.html
Demonstrates a series of functions that conceptually throw exceptions, highlighting the difficulty in tracking and composing such operations.
```kotlin
val throwsSomeStuff: (Int) -> Double = {x -> x.toDouble()}
val throwsOtherThings: (Double) -> String = {x -> x.toString()}
val moreThrowing: (String) -> List = {x -> listOf(x)}
val magic: (Int) -> List = { x ->
val y = throwsSomeStuff(x)
val z = throwsOtherThings(y)
moreThrowing(z)
}
fun main() {
println ("magic = $magic")
}
```
--------------------------------
### getAbsentValue Function
Source: https://apidocs.arrow-kt.io/arrow-core-jackson2/arrow.integrations.jackson.module/-non-empty-collection-deserializer/index.html
Gets the absent value for the deserializer.
```APIDOC
## getAbsentValue Function
### Description
Gets the absent value for the deserializer.
### Signature
open fun getAbsentValue(ctxt: DeserializationContext?): Any?
```
--------------------------------
### Loading User Info with AwaitAllScope
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines.await/-await-all-scope/index.html
Demonstrates how to use AwaitAllScope to concurrently load user information. When `name.await()` is called, all other async operations within the scope are also awaited, ensuring all data is ready.
```kotlin
suspend fun loadUserInfo(id: UserId): UserInfo = await {
val name = async { loadUserFromDb(id) }
val avatar = async { loadAvatar(id) }
UserInfo(
name.await(), // <- at this point every 'async' is 'await'ed
avatar.await() // <- so when you reach this 'await', the value is already there
)
}
```
--------------------------------
### get
Source: https://apidocs.arrow-kt.io/arrow-core/arrow.core/-non-empty-list/index.html
Retrieves the element at the specified index from the NonEmptyList.
```APIDOC
## get
### Description
Retrieves the element at the specified index from the NonEmptyList.
### Signature
`open operator override fun get(index: Int): E`
```
--------------------------------
### get
Source: https://apidocs.arrow-kt.io/arrow-atomic/arrow.atomic/-atomic/index.html
Retrieves the current value of the atomic reference.
```APIDOC
## Functions
### get
**Description**: Returns the current value of the atomic reference.
**Availability**: Common, non-JVM
#### Syntax
```kotlin
// expect function
fun get(): V
// actual function
fun get(): V
```
```
--------------------------------
### Resource Definition and Composition
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Shows how to define and compose resources using Arrow Fx Coroutines' `resource` function and `resourceScope` for safe acquisition and release.
```kotlin
val userProcessor: Resource = resource({
UserProcessor().also { it.start() }
}) { p, _ -> p.shutdown() }
val dataSource: Resource = resource({
DataSource().also { it.connect() }
}) { ds, exitCase ->
println("Releasing $ds with exit: $exitCase")
withContext(Dispatchers.IO) { ds.close() }
}
val service: Resource = resource {
Service(dataSource.bind(), userProcessor.bind())
}
suspend fun main(): Unit = resourceScope {
val data = service.bind().processData()
println(data)
}
```
--------------------------------
### AtomicInt.get
Source: https://apidocs.arrow-kt.io/arrow-atomic/arrow.atomic/-atomic-int/index.html
Gets the current value of the atomic integer.
```APIDOC
## Function get
### Description
Retrieves the current value of the `AtomicInt`.
### Method
`get(): Int`
```
--------------------------------
### Try Acquire Multiple Permits
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-s-t-m/try-acquire.html
Demonstrates attempting to acquire three permits from a TSemaphore initialized with zero permits. This will return false as no permits are available.
```kotlin
import arrow.fx.stm.TSemaphore
import arrow.fx.stm.atomically
suspend fun main() {
//sampleStart
val tsem = TSemaphore.new(0)
val result = atomically {
tsem.tryAcquire(3)
}
//sampleEnd
println("Result $result")
println("Permits remaining ${atomically { tsem.available() }}")
}
```
--------------------------------
### Unsafe Resource Management Example
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Demonstrates a common pattern of resource management that is prone to leaks due to exceptions or cancellations.
```kotlin
class UserProcessor {
fun start(): Unit = println("Creating UserProcessor")
fun shutdown(): Unit = println("Shutting down UserProcessor")
}
class DataSource {
fun connect(): Unit = println("Connecting dataSource")
fun close(): Unit = println("Closed dataSource")
}
class Service(val db: DataSource, val userProcessor: UserProcessor) {
suspend fun processData(): List = throw RuntimeException("I'm going to leak resources by not closing them")
}
suspend fun main(): Unit {
val userProcessor = UserProcessor().also { it.start() }
val dataSource = DataSource().also { it.connect() }
val service = Service(dataSource, userProcessor)
service.processData()
dataSource.close()
userProcessor.shutdown()
}
```
--------------------------------
### at(i: I): Lens
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics.typeclasses/-at/at.html
Get a Lens for a structure S with focus in A at index i.
```APIDOC
## at(i: I): Lens
### Description
Get a Lens for a structure S with focus in A at index i.
### Parameters
- **i** (I) - index I to zoom into S and find focus A
### Return
Lens with a focus in A at given index I.
```
--------------------------------
### get
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-iso/index.html
Retrieves all elements of type A from a List within a PLens.
```APIDOC
## get
### Description
Retrieves all elements of type A from a List within a PLens.
### Method
Operator Function
### Parameters
#### Type Parameters
- **A**: The type of elements in the list.
- **T**: The type of the structure containing the list.
- **PLens, List>**: The PLens focusing on the list.
#### Parameters
- **i**: Int - The index of the element to retrieve (this parameter seems misplaced in the context of a PLens focusing on a List, typically `get` on a PLens would return the whole List).
- **source**: T - The data structure containing the list.
```
--------------------------------
### Resource from Extension Function Reference
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines/-resource/index.html
Creates a resource by directly referencing an extension function that installs and releases resources. This provides a clean and reusable way to define resources.
```kotlin
val userProcessor3: Resource = ResourceScope::userProcessor
```
--------------------------------
### index (Traversal - Sequence)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get an element from a Sequence by index.
```APIDOC
@JvmName(name = "indexSequence")
fun Traversal>.index(index: Int): Traversal
```
--------------------------------
### Creating TArray Instances
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-t-array/index.html
Demonstrates various ways to create a TArray, including specifying size, initial values, and populating from iterables or varargs.
```kotlin
TArray.new(10) { i -> i * 2 }
```
```kotlin
TArray.new(size = 10, 2)
```
```kotlin
TArray.new(5, 2, 10, 600)
```
```kotlin
TArray.new(listOf(5,4,3,2))
```
--------------------------------
### index (Traversal - Map)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get a value from a Map by key.
```APIDOC
@JvmName(name = "indexValues")
fun Traversal>.index(key: K): Traversal
```
--------------------------------
### Loading User Info without AwaitAllScope
Source: https://apidocs.arrow-kt.io/arrow-fx-coroutines/arrow.fx.coroutines.await/-await-all-scope/index.html
Illustrates the manual approach to awaiting multiple deferred computations using `awaitAll`. This is necessary when not using AwaitAllScope, as deferred values are not automatically awaited.
```kotlin
suspend fun loadUserInfoWithoutAwait(id: UserId): UserInfo {
val name = async { loadUserFromDb(id) }
val avatar = async { loadAvatar(id) }
awaitAll(name, avatar) // <- this is required otherwise
return UserInfo(
name.await(),
avatar.await()
)
}
```
--------------------------------
### Creating a new TMVar
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-t-m-var/index.html
Demonstrates how to create a new TMVar with an initial value using `TMVar.new` and how to atomically take the value.
```APIDOC
## Creating a new TMVar
This operation creates a new TMVar with an initial value and demonstrates how to atomically take that value.
### Method
`TMVar.new(value: A)` and `STM.newTMVar(value: A)`
### Usage
```kotlin
import arrow.fx.stm.TMVar
import arrow.fx.stm.atomically
suspend fun main() {
val tmvar = TMVar.new(10)
val result = atomically { tmvar.take() }
println("Result: $result")
println("New value: ${atomically { tmvar.tryTake() } }")
}
```
### Notes
- If the TMVar is empty when `take()` is called within an STM transaction, the transaction will retry and wait until a value is available.
- `tryTake()` can be used to attempt to take the value without retrying if the TMVar is empty, returning null in that case.
```
--------------------------------
### index (Traversal - List)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get an element from a List by index.
```APIDOC
fun Traversal>.index(index: Int): Traversal
```
--------------------------------
### index (Traversal - String)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get a character from a String by index.
```APIDOC
@JvmName(name = "indexString")
fun Traversal.index(index: Int): Traversal
```
--------------------------------
### Creating TArray
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-t-array/index.html
Demonstrates various ways to create a TArray, including specifying size, initial value, varargs, and iterables.
```APIDOC
## Creating TArray
Similar to normal arrays there are a few ways to create a TArray:
```kotlin
import arrow.fx.stm.TArray
import arrow.fx.stm.atomically
suspend fun example() {
//sampleStart
// Create a size 10 array and fill it by using the construction function.
TArray.new(10) { i -> i * 2 }
// Create a size 10 array and fill it with a constant
TArray.new(size = 10, 2)
// Create an array from `vararg` arguments:
TArray.new(5, 2, 10, 600)
// Create an array from any iterable
TArray.new(listOf(5,4,3,2))
//sampleEnd
}
```
```
--------------------------------
### index (Traversal - NonEmptyList)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get an element from a NonEmptyList by index.
```APIDOC
@JvmName(name = "indexNonEmptyList")
fun Traversal>.index(index: Int): Traversal
```
--------------------------------
### Create and Write to TQueue
Source: https://apidocs.arrow-kt.io/arrow-fx-stm/arrow.fx.stm/-t-queue/index.html
Demonstrates creating a new TQueue and writing elements to it using the write and += operators within an atomic transaction.
```kotlin
import arrow.fx.stm.TQueue
import arrow.fx.stm.atomically
suspend fun main() {
//sampleStart
val tq = TQueue.new()
atomically {
tq.write(2)
// or alternatively
tq += 4
}
//sampleEnd
println("Items in queue ${atomically { tq.flush() }}")
}
```
--------------------------------
### Nested copy using Arrow Optics copy DSL
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/copy.html
This example shows how to use the Arrow Optics copy DSL for a more concise and readable way to update nested immutable data structures.
```kotlin
person.copy {
Person.address.city set "Madrid"
}
```
--------------------------------
### index (Optional - Sequence)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get an element from a Sequence by index.
```APIDOC
@JvmName(name = "indexSequence")
fun Optional>.index(index: Int): Optional
```
--------------------------------
### index (Optional - Map)
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-lens/index.html
Get a value from a Map by key.
```APIDOC
@JvmName(name = "indexValues")
fun Optional>.index(key: K): Optional
```
--------------------------------
### first
Source: https://apidocs.arrow-kt.io/arrow-optics/arrow.optics/-p-iso/index.html
Creates a pair of the PIso and a type C, effectively pairing the PIso's functionality with another type.
```APIDOC
## first
### Description
Create a pair of the PIso and a type C.
### Method
Extension Function
### Parameters
#### Type Parameters
- **C**: The type of the second element in the pair.
- **PIso, Pair, Pair, Pair>**: The resulting PIso type.
#### Extension Receiver
- **PIso** (Implicitly used via context, not directly in signature)
#### Parameters
None.
```