Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Last active April 18, 2018 05:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvolpe/0f9e626e2091fa98feaf296e73db6637 to your computer and use it in GitHub Desktop.
Save gvolpe/0f9e626e2091fa98feaf296e73db6637 to your computer and use it in GitHub Desktop.
IO, Bracket and Cancelation
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
}
}
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