Last active
May 25, 2024 10:20
-
-
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/f04505f41810189fff3cdf93859e01d107535a39
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 - 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.4.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