Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active November 28, 2023 15:42
Show Gist options
  • Save sshark/c8b1d26d41b4d1cdb89d5857ffc7ba17 to your computer and use it in GitHub Desktop.
Save sshark/c8b1d26d41b4d1cdb89d5857ffc7ba17 to your computer and use it in GitHub Desktop.
Demonstrate cancellable tasks are cancelled while they are sleeping
package org.teckhooi.dojo3.concurrent
import cats.effect.{IO, IOApp}
import scala.concurrent.duration.*
object CancellableTask extends IOApp.Simple {
def task(i: Int, d: Duration): IO[Unit] = IO.sleep(d) *> IO.println(s"Task $i completed")
override def run: IO[Unit] = for {
f <- IO.uncancelable(poll => poll(task(1, 2.second)) *> task(2, 1500.millis) *> poll(task(3, 2.second))).start
_ <- IO.sleep(3.seconds) *> f.cancel
} yield ()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment