Skip to content

Instantly share code, notes, and snippets.

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/9662781f250d6b4993096b6e006fa455 to your computer and use it in GitHub Desktop.
Save dacr/9662781f250d6b4993096b6e006fa455 to your computer and use it in GitHub Desktop.
ZIO learning - managed resource using acquireReleaseWith approach / published by https://github.com/dacr/code-examples-manager #23b9338f-29dd-46a1-8a47-30a1fc22ace6/7fb323ba63c9d060344f182415ddc2cc229f0171
// summary : ZIO learning - managed resource using acquireReleaseWith approach
// keywords : scala, zio, learning, pure-functional, resources, acquire, auto-release, @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 : 23b9338f-29dd-46a1-8a47-30a1fc22ace6
// created-on : 2021-04-02T15:36:11+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"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
// ---------------------
import zio.*, zio.worksheet.*
import java.io.*
val acquireFile = ZIO.attemptBlockingIO(File.createTempFile("truc-", ".tmp"))
def releaseFile(file: File) = {
ZIO.attemptBlockingIO(file.delete)
.catchAll(ex => ZIO.logError(s"Couldn't delete file $file ${ex.getMessage}"))
}
def acquirePrintStream(file: File) = ZIO.attemptBlockingIO(new PrintStream(file))
def releasePrintStream(printStream: PrintStream) = {
ZIO.attemptBlockingIO(printStream.close()).catchAll(ex => ZIO.logError(s"Couldn't close file ${ex.getMessage}"))
}
def acquireReadStream(file: File) = ZIO.attemptBlockingIO(new BufferedReader(new FileReader(file)))
def releaseReadStream(reader: BufferedReader) = {
ZIO.attemptBlockingIO(reader.close())
.catchAll(ex => ZIO.logError(s"Couldn't close reader ${ex.getMessage}"))
}
def fileIO(content: String)(file: File) = {
ZIO
.acquireReleaseWith(acquirePrintStream(file))(releasePrintStream) { printStream =>
ZIO.attemptBlockingIO(printStream.println(content))
}
.flatMap(_ =>
ZIO.acquireReleaseWith(acquireReadStream(file))(releaseReadStream) { reader =>
ZIO.attemptBlockingIO(reader.readLine())
}
)
}
val writeLogic = ZIO.acquireReleaseWith(acquireFile)(releaseFile)(fileIO("Hello world"))
val content = writeLogic.unsafeRun
println(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment