arrow-fx-coroutines / arrow.fx.coroutines / Atomic

Atomic

interface Atomic<A>

Creates a AtomicRef with a initial value of A.

Data type on top of atomic to use in parallel functions.

import arrow.fx.coroutines.*

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

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

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

Functions

access Obtain a snapshot of the current value, and a setter for updating it.abstract suspend fun access(): Pair<A, suspend (A) -> Boolean>
get Obtains the current value. Since AtomicRef is always guaranteed to have a value, the returned action completes immediately after being bound.abstract suspend fun get(): A
getAndSet Replaces the current value with a, returning the old value.abstract suspend fun getAndSet(a: A): A
getAndUpdate Modifies the current value using the supplied update function and returns the old value.abstract suspend fun getAndUpdate(f: (A) -> A): A
lens Creates a AtomicRef for B based on provided a get and set operation.open fun <B> lens(get: (A) -> B, set: (A, B) -> A): Atomic<B>
modify Modify allows to inspect the state A of the AtomicRef, update it and extract a different state B.abstract suspend fun <B> modify(f: (A) -> Pair<A, B>): B
modifyGet ModifyGet allows to inspect state A, update it and extract a different state B. In contrast to modify it a Pair of the updated state A and the extracted state B.abstract suspend fun <B> modifyGet(f: (A) -> Pair<A, B>): Pair<A, B>
set Sets the current value to a. The returned action completes after the reference has been successfully set.abstract suspend fun set(a: A): Unit
setAndGet Replaces the current value with a, returning the new value.abstract suspend fun setAndGet(a: A): A
tryModify Like tryUpdate but allows the update function to return an output value of type B.abstract suspend fun <B> tryModify(f: (A) -> Pair<A, B>): B?
tryUpdate Attempts to modify the current value once, in contrast to update which calls f until it succeeds.abstract suspend fun tryUpdate(f: (A) -> A): Boolean
update Updates the current value using the supplied function f.abstract suspend fun update(f: (A) -> A): Unit
updateAndGet Modifies the current value using the supplied update function and returns the new value.abstract suspend fun updateAndGet(f: (A) -> A): A

Companion Object Functions

invoke Creates a AtomicRef with a initial value of A.suspend operator fun <A> invoke(a: A): Atomic<A>
unsafe fun <A> unsafe(a: A): Atomic<A>

Inheritors

SignallingAtomic Pure holder of a single atomic value of type A that can be both read and updated. Composes Signal and Atomic together to make an signalling atomic value.class SignallingAtomic<A> : Atomic<A>, Signal<A>

Do you like Arrow?

Arrow Org
<