I want that user can run a timer with callback and able to cancel it. Something like this:
def main: F[Unit] =
for
cancel <- runTimer(callback, 5.seconds)
shouldCancel <- askUser
_ <- cancel.whenA(shouldCancel)
yield ()
How can I do it in terms of Cats of FS2?
The code that you need is actually pretty simple thanks to cats-effect being very powerful at solving concurrency problems:
The key aspects are as follows:
IO.sleepto delay the execution of the callback.uncancelableto make the callback uncancelable.IO.raceto run both the delayed callback and the cancel concurrently. If thecancelcompletes before the delay, theracewill cancel the execution of the callback.You can see a demo of the code running here: https://scastie.scala-lang.org/BalmungSan/UP6N6wMBTQGLHPjOmXS9mw/1