Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/2a8bc6eb61100cfaefcab9b43c399da4 to your computer and use it in GitHub Desktop.
Save dacr/2a8bc6eb61100cfaefcab9b43c399da4 to your computer and use it in GitHub Desktop.
ZIO learning - effectfully atomic update like operations / published by https://github.com/dacr/code-examples-manager #a4cfd379-4365-45cb-84df-ab080f94c76a/79eae8af791fdcb1475bc4318090fda97a194130
// summary : ZIO learning - effectfully atomic update like operations
// keywords : scala, zio, learning, pure-functional, @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 : a4cfd379-4365-45cb-84df-ab080f94c76a
// created-on : 2021-04-06T15:32:12+02:00
// 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"
// ---------------------
import zio.*
object Encapsulated extends ZIOAppDefault {
// Ref[A] : is a "mutable" cell that contains a reference to an A that may be updated atomically
// Ref.Synchonized[A] : is a "mutable" cell that contains a reference to an A that may be updated atomically and effectfully!
val ages = Map(1 -> 12, 2 -> 42, 3 -> 35, 4 -> 54, 6 -> 17, 7 -> 99)
val users = ages.keys
def apiGetAge(userId: Int) = ZIO.fromOption(ages.get(userId))
def run = {
for {
ref <- Ref.Synchronized.make(0)
_ <- ZIO.foreachPar(users)(id => ref.updateZIO(cur => apiGetAge(id).map(_ + cur)))
sum <- ref.get
mean = sum / users.size
_ <- Console.printLine(s"mean=$mean")
} yield mean
}
}
Encapsulated.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment