arrow-fx-stm / arrow.fx.stm / STM / read

read

abstract fun <A> TVar<A>.read(): A

Read the value from a TVar.

import arrow.fx.stm.TVar
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tvar = TVar.new(10)
  val result = atomically {
    tvar.read()
  }
  //sampleEnd
  println(result)
}

This comes with a few guarantees:

  • Any given TVar is only ever read once during a transaction.
  • When committing the transaction the value read has to be equal to the current value otherwise the transaction will retry open fun <A> TMVar<A>.read(): A

Read a value from a TMVar without removing it.

import arrow.fx.stm.TMVar
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tmvar = TMVar.new(30)
  val result = atomically {
    tmvar.read()
  }
  //sampleEnd
  println("Result $result")
  println("New value ${atomically { tmvar.tryTake() } }")
}

This retries if the TMVar is empty but does not take the value out if it succeeds.

See Also

TMVar.tryRead

TMVar.take

open fun <A> TQueue<A>.read(): A

Remove the front element from the TQueue or retry if the TQueue is empty.

import arrow.fx.stm.TQueue
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tq = TQueue.new<Int>()
  val result = atomically {
    tq.write(2)
    tq.read()
  }
  //sampleEnd
  println("Result $result")
  println("Items in queue ${atomically { tq.flush() }}")
}

See Also

TQueue.tryRead

TQueue.peek

Do you like Arrow?

Arrow Org
<