Created
March 17, 2019 21:49
-
-
Save felher/6f039f96416a44b2069c1499b1c2bbcb to your computer and use it in GitHub Desktop.
bracket and cancel
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
starting A | |
^Cstarting B | |
stopping B | |
stopping A |
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
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 |
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
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