Last active
May 6, 2023 15:40
-
-
Save dacr/dd25453d53fb97da0cef816b6f8791e5 to your computer and use it in GitHub Desktop.
ZIO learning - transactions / published by https://github.com/dacr/code-examples-manager #382b643a-6998-4726-82e5-9d8080f5ac26/2a7da815d483f486b640af3bcdbed4b61bbcf30c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : ZIO learning - transactions | |
// keywords : scala, zio, learning, pure-functional, transactions, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 382b643a-6998-4726-82e5-9d8080f5ac26 | |
// created-on : 2021-11-06T08:14:16Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.2.2" | |
//> using dep "dev.zio::zio:2.0.13" | |
// --------------------- | |
/* | |
inspired from https://zio.dev/datatypes/stm/stm | |
*/ | |
import zio.* | |
import zio.stm.* | |
import java.io.IOException | |
object Encapsulated extends ZIOAppDefault { | |
def transferMoney(from: TRef[Long], to: TRef[Long], amount: Long): STM[String, (Long, Long)] = | |
for { | |
senderBalance <- from.get | |
_ <- if (senderBalance < amount) STM.fail("Not enough money") else STM.unit | |
_ <- from.update(existing => existing - amount) | |
_ <- to.update(existing => existing + amount) | |
senderBalance <- from.get | |
receiverBalance <- to.get | |
} yield (senderBalance, receiverBalance) | |
val app: ZIO[Any, IOException | String, (Long, Long)] = for { | |
senderAccount <- STM.atomically(TRef.make(1000L)) | |
receiverAccount <- STM.atomically(TRef.make(0L)) | |
result <- STM.atomically(transferMoney(senderAccount, receiverAccount, 420L)) | |
_ <- Console.printLine(result) | |
} yield result | |
def run = app | |
} | |
Encapsulated.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment