Created
June 24, 2019 11:08
-
-
Save iRevive/67b71431c00a5d7521cbfe48334e0224 to your computer and use it in GitHub Desktop.
Fiber cancellation
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.effect.{ExitCase, ExitCode, IO, IOApp} | |
import cats.syntax.flatMap._ | |
import cats.syntax.functor._ | |
import scala.concurrent.duration._ | |
object UncancelableApp extends IOApp { | |
override def run(args: List[String]): IO[ExitCode] = { | |
val job: IO[String] = for { | |
sessionId <- allocateSession.uncancelable | |
_ <- verifySession(sessionId).guaranteeCase { | |
case ExitCase.Completed => IO.unit | |
case ExitCase.Canceled => terminateSession(sessionId) | |
case ExitCase.Error(_) => terminateSession(sessionId) | |
} | |
} yield sessionId | |
for { | |
fiber <- job.start | |
_ <- log("Started") | |
_ <- fiber.cancel | |
_ <- log("Cancelled") | |
_ <- IO.sleep(5.seconds) | |
} yield ExitCode.Success | |
} | |
def allocateSession: IO[String] = | |
log("Allocating session") >> IO.sleep(3.seconds).as("session_1") | |
def verifySession(sessionId: String): IO[Unit] = | |
log(s"Verifying session [$sessionId]") | |
def terminateSession(sessionId: String): IO[Unit] = | |
log(s"Terminating session [$sessionId]") | |
def log(message: String): IO[Unit] = | |
IO.delay(println(s"${System.currentTimeMillis()} ${Thread.currentThread().getName}: $message")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment