TVar
A TVar
(transactional variable) is a mutable memory location that can be be
read and modified via Txn
actions.
import cats.effect.IO
import cats.effect.unsafe.implicits.global
import io.github.timwspence.cats.stm.STM
val stm = STM.runtime[IO].unsafeRunSync()
// stm: STM[IO] = io.github.timwspence.cats.stm.STM$Make$$anon$1$$anon$2@24255fb
import stm._
val to = stm.commit(TVar.of(1)).unsafeRunSync()
// to: TVar[Int] = io.github.timwspence.cats.stm.STMLike$TVar@1ed7fbd2
val from = stm.commit(TVar.of(0)).unsafeRunSync()
// from: TVar[Int] = io.github.timwspence.cats.stm.STMLike$TVar@66b045ea
val txn: Txn[(Int, Int)] = for {
balance <- from.get
_ <- from.modify(_ - balance)
_ <- to.modify(_ + balance)
res1 <- from.get
res2 <- to.get
} yield res1 -> res2
// txn: Txn[(Int, Int)] = Bind(
// txn = Get(tvar = io.github.timwspence.cats.stm.STMLike$TVar@66b045ea),
// f = <function1>
// )
val result = stm.commit(txn).unsafeRunSync()
// result: (Int, Int) = (0, 1)
Note that this does not modify either from
or to
!! It merely describes a
transaction which must be executed via STM#commit