Let's say I have a following method signature in a project using Cats-effect
and tagless final approach:
def schedule[F[_]: Applicative : Async: Timer]
I'm trying to schedule an operation on a schedule
method call using pure FP.
I tried this way:
Timer[F].sleep(FiniteDuration(10, TimeUnit.SECONDS)) *> {
Applicative[F].pure(println("tick"))
}
but it didn't work, because effect println("tick")
gets executed on Timer
initialisation stage.
How can I make it works properly?
Can I also create some kind of recursive construction in order to repeat my scheduled operation each 10 seconds?
Applicative[F].pure
doesn't delay the effect. It only lifts a pure value into F
. Since you have an Async
context bound I would suggest Async[F].delay(println("tick"))
.
You can easily call it recursively like this:
def schedule[F[_]: Async: Timer]: F[Unit]
def repeat[F[_]: Async: Timer]: F[Unit] =
schedule >> repeat