Last active
May 25, 2024 10:20
-
-
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/9cc238c98997b0713c3890195d010ca7066b71f9
This file contains hidden or 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.4.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