Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:18
Show Gist options
  • Save dacr/6375501d53b9971107ac31692d83a756 to your computer and use it in GitHub Desktop.
Save dacr/6375501d53b9971107ac31692d83a756 to your computer and use it in GitHub Desktop.
ZIO learning - race to get the fastest response and immediately stop others / published by https://github.com/dacr/code-examples-manager #0eb518fe-7323-4858-9a50-7137d90eb998/91bdcf36efd85b7ce3ffaadbc5744e5e6975ae5d
// summary : ZIO learning - race to get the fastest response and immediately stop others
// 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 : 0eb518fe-7323-4858-9a50-7137d90eb998
// created-on : 2021-04-06T11:07:45+02:00
// 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"
// ---------------------
import zio.*
object ThatApp extends ZIOAppDefault {
def sha(that: String, algo: String) = {
for {
md <- ZIO.attempt(java.security.MessageDigest.getInstance(algo))
digest <- ZIO.attempt(md.digest(that.getBytes))
bigInt <- ZIO.attempt(new java.math.BigInteger(1, digest))
hashedString = bigInt.toString(16)
} yield hashedString
}
def sha1(that: String) = sha(that, "SHA-1")
def sha256(that: String) = sha(that, "SHA-256")
val message = "Hello world"
val racedTasks = sha256(message).race(sha1(message))
val run = for {
result <- racedTasks
_ <- Console.printLine(result)
} yield ()
}
// -------------------------------------------------------------
ThatApp.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment