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

Atomic

common 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

Name Summary
Companion common object Companion

Functions

Name Summary
access common abstract suspend fun access(): Pair<A, suspend (A) -> Boolean>
Obtains a snapshot of the current value, and a setter for updating it.
get common 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.
getAndSet common abstract suspend fun getAndSet(a: A): A
Replaces the current value with a, returning the old value.
getAndUpdate common abstract suspend fun getAndUpdate(f: (A) -> A): A
Modifies the current value using the supplied update function and returns the old value.
lens common 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.
modify common 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.
modifyGet common 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.
set common abstract suspend fun set(a: A)
Sets the current value to a. The returned action completes after the reference has been successfully set.
setAndGet common abstract suspend fun setAndGet(a: A): A
Replaces the current value with a, returning the new value.
tryModify common abstract suspend fun <B> tryModify(f: (A) -> Pair<A, B>): B?
Attempts to inspect the state, uptade it, and extract a different state.
tryUpdate common 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.
update common abstract suspend fun update(f: (A) -> A)
Updates the current value using the supplied function f.
updateAndGet common abstract suspend fun updateAndGet(f: (A) -> A): A
Modifies the current value using the supplied update function and returns the new value.

Do you like Arrow?

Arrow Org
<