Last active
April 18, 2018 05:34
-
-
Save gvolpe/0f9e626e2091fa98feaf296e73db6637 to your computer and use it in GitHub Desktop.
IO, Bracket and Cancelation
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
import java.io.FileOutputStream | |
import cats.effect.ExitCase.{Canceled, Completed, Error} | |
import cats.effect._ | |
import cats.syntax.apply._ | |
import cats.syntax.functor._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
object Bracketing extends IOApp { | |
// --- Bracketing simple example --- | |
val bracketingExample: IO[Unit] = { | |
val acquireResource: IO[FileOutputStream] = | |
IO { new FileOutputStream("test.txt") } | |
val useResource: FileOutputStream => IO[Unit] = | |
fos => IO { fos.write("test data".getBytes()) } | |
val releaseResource: FileOutputStream => IO[Unit] = | |
fos => IO { fos.close() } | |
val ioa = acquireResource.bracket(useResource)(releaseResource) | |
val iob = putStrLn("acquiring").bracket { _ => | |
putStrLn("using") *> IO.raiseError(new Exception("boom!")) | |
} { _ => | |
putStrLn("releasing") | |
} | |
ioa *> iob | |
} | |
// --- Bracketing and Cancelation example --- | |
val bracketingOnCancelationExample: IO[Unit] = { | |
val releasing: (String, ExitCase[Throwable]) => IO[Unit] = { | |
case (x, Completed | Error(_)) => putStrLn(s"releasing $x on complete or error") | |
case (x, Canceled(_)) => putStrLn(s"releasing $x on cancelation") | |
} | |
val ioa = IO("A").bracketCase(putStrLn)(releasing) | |
val iob = IO("B").bracketCase(x => IO.sleep(1.second) *> putStrLn(x))(releasing) | |
IO.race(ioa, iob).void | |
} | |
override def start(args: List[String]): IO[Unit] = { | |
bracketingOnCancelationExample | |
} | |
} |
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
import cats.effect.IO | |
trait IOApp { | |
def start(args: List[String]): IO[Unit] | |
def putStrLn(value: String): IO[Unit] = IO { println(value) } | |
def main(args: Array[String]): Unit = start(args.toList).unsafeRunSync() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment