Created
April 9, 2019 00:44
-
-
Save mitsutaka-takeda/1928a10fd7356124cb53756a3a659f14 to your computer and use it in GitHub Desktop.
How to manage resources with Scalaz.ZIO
This file contains 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
// Add in build.sbt | |
// | |
// scalaVersion := "2.12.8" | |
// | |
// libraryDependencies ++= Seq( | |
// "org.scalaz" %% "scalaz-zio" % "0.18", | |
// "org.scalatest" %% "scalatest" % "3.0.0" % "test" | |
// ) | |
import org.scalatest.{Matchers, WordSpecLike} | |
import scalaz.zio._ | |
class MyResource(var closed: Boolean) { | |
println("1. created") | |
def close(): Unit = { | |
println("3. closed") | |
closed = true | |
} | |
def doSomething: Boolean = { | |
require(!closed) | |
true | |
} | |
} | |
class BadManagementTest extends WordSpecLike with Matchers with DefaultRuntime { | |
val myResource: ZManaged[Any, Nothing, MyResource] = ZManaged.make(ZIO.succeed({ | |
new MyResource(false) | |
})){ m => UIO.effectTotal(m.close())} | |
"Resource" should { | |
"not outlive its scope" in { | |
val result = unsafeRun(myResource.use( | |
r => | |
for { | |
b <- ZIO.succeed(r.doSomething) | |
} yield b | |
)) | |
result shouldBe true | |
} | |
} | |
"Multiple use of a resource" should { | |
"fail" in { | |
// this test fails because the resource is already closed in the first test above. | |
val result = unsafeRun(myResource.use( | |
r => | |
for { | |
b <- ZIO.succeed(r.doSomething) | |
} yield b | |
)) | |
result shouldBe true | |
} | |
} | |
} | |
class GoodManagementTest extends WordSpecLike with Matchers with DefaultRuntime { | |
val myResourceIO: Task[ZManaged[Any, Nothing, MyResource]] = ZIO.effect(ZManaged.make(ZIO.succeed({ | |
new MyResource(false) | |
})){ m => UIO.effectTotal(m.close())}) | |
"Resource" should { | |
"not outlive its scope" in { | |
val result = unsafeRun( | |
for { | |
myResource <- myResourceIO | |
r <- myResource.use( | |
r => | |
for { | |
b <- ZIO.succeed(r.doSomething) | |
} yield b | |
) | |
} yield r) | |
result shouldBe true | |
} | |
} | |
"Multiple use of a resource" should { | |
"not fail" in { | |
// | |
val result = unsafeRun( | |
for { | |
myResource <- myResourceIO | |
r <- myResource.use( | |
r => | |
for { | |
b <- ZIO.succeed(r.doSomething) | |
} yield b | |
) | |
} yield r) | |
result shouldBe true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment