//arrow-fx-stm/arrow.fx.stm/STM/swap

swap

common open fun <A> TVar<A>.swap(a: A): A

Swap the content of the TVar

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

suspend fun main() {
  //sampleStart
  val tvar = TVar.new(10)
  val result = atomically {
    tvar.swap(20)
  }
  //sampleEnd
  println("Result $result")
  println("New value ${tvar.unsafeRead()}")
}

Return

The previous value stored inside the TVar

common open fun <A> TMVar<A>.swap(a: A): A

Swap the content of a TMVar or retry if it is empty.

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

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

Do you like Arrow?

Arrow Org
<