Skip to content

Instantly share code, notes, and snippets.

@felher
Created March 17, 2019 21:49
Show Gist options
  • Save felher/6f039f96416a44b2069c1499b1c2bbcb to your computer and use it in GitHub Desktop.
Save felher/6f039f96416a44b2069c1499b1c2bbcb to your computer and use it in GitHub Desktop.
bracket and cancel
starting A
^Cstarting B
stopping B
stopping A
starting A
starting B
starting C
^Cstarting D
doing main work
doing main work
doing main work
doing main work
doing main work
doing main work
stopping D
stopping C
stopping B
stopping A
import cats.implicits._, cats.effect._
object Main extends IOApp {
def run(args: List[String]): IO[ExitCode] =
startAllCancelable(mainWork, List(testStarter("A"), testStarter("B"), testStarter("C"), testStarter("D"))).as(ExitCode.Success)
def startAllCancelable[A](mainWork: IO[A], taskStarters: List[IO[Fiber[IO, Unit]]]): IO[A] =
taskStarters.foldRight(mainWork)((t, w) => t.bracket(_ => w)(_.cancel))
def mainWork: IO[Unit] =
IO { println("doing main work"); } *> IO { Thread.sleep(1000) } *> IO { println("doing main work"); } *> IO { Thread.sleep(1000) } *> IO { println("doing main work"); } *> IO { Thread.sleep(1000) } *>
IO { println("doing main work"); } *> IO { Thread.sleep(1000) } *> IO { println("doing main work"); } *> IO { Thread.sleep(1000) } *> IO { println("doing main work"); } *> IO { Thread.sleep(1000) }
def testStarter(s: String): IO[Fiber[IO, Unit]] =
IO { Thread.sleep(1000) } *> (IO { println("starting " + s) } *> IO.never).void.guarantee(IO { println("stopping " + s) }).start
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment