Atomic

interface Atomic<A>

An Atomic with an initial value of A.

Atomic wraps atomic, so that you can also use it on a top-level function or pass it around. In other languages this data type is also known as Ref, IORef or Concurrent safe Reference. So in case you don't need to pass around an atomic reference, or use it in top-level functions it's advised to use atomic from Atomic Fu directly.

import arrow.fx.coroutines.*

suspend fun main() {
val count = Atomic(0)

(0 until 20_000).parTraverse {
count.update(Int::inc)
}
println(count.get())
}

Atomic also offers some other interesting operators such as modify, tryUpdate, access&lens.

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
abstract suspend fun access(): Pair<A, suspend (A) -> Boolean>

Obtains a snapshot of the current value, and a setter for updating it.

Link copied to clipboard
abstract suspend fun get(): A

Obtains the current value. Since AtomicRef is always guaranteed to have a value, the returned action completes immediately after being bound.

Link copied to clipboard
abstract suspend fun getAndSet(a: A): A

Replaces the current value with a, returning the old value.

Link copied to clipboard
abstract suspend fun getAndUpdate(f: (A) -> A): A

Modifies the current value using the supplied update function and returns the old value.

Link copied to clipboard
open fun <B> lens(get: (A) -> B, set: (A, B) -> A): Atomic<B>

Creates an AtomicRef for B based on provided a get and set operation.

Link copied to clipboard
abstract suspend fun <B> modify(f: (A) -> Pair<A, B>): B

Modify allows to inspect the state A of the AtomicRef, update it and extract a different state B.

Link copied to clipboard
abstract suspend fun <B> modifyGet(f: (A) -> Pair<A, B>): Pair<A, B>

ModifyGet allows to inspect state A, update it and extract a different state B. In contrast to modify, it returns a Pair of the updated state A and the extracted state B.

Link copied to clipboard
abstract suspend fun set(a: A)

Sets the current value to a. The returned action completes after the reference has been successfully set.

Link copied to clipboard
abstract suspend fun setAndGet(a: A): A

Replaces the current value with a, returning the new value.

Link copied to clipboard
abstract suspend fun <B> tryModify(f: (A) -> Pair<A, B>): B?

Attempts to inspect the state, uptade it, and extract a different state.

Link copied to clipboard
abstract suspend fun tryUpdate(f: (A) -> A): Boolean

Attempts to modify the current value once, in contrast to update which calls f until it succeeds.

Link copied to clipboard
abstract suspend fun update(f: (A) -> A)

Updates the current value using the supplied function f.

Link copied to clipboard
abstract suspend fun updateAndGet(f: (A) -> A): A

Modifies the current value using the supplied update function and returns the new value.