假设我在使用Cats-effect和无标记最终方法的项目中有以下方法签名:
def schedule[F[_]: Applicative : Async: Timer]我正在尝试使用纯FP在schedule方法调用上安排一个操作。
我试过这样做:
Timer[F].sleep(FiniteDuration(10, TimeUnit.SECONDS)) *> {
Applicative[F].pure(println("tick"))
}但它不起作用,因为effect println("tick")是在Timer初始化阶段执行的。
我怎样才能让它正常工作?
我还可以创建某种递归构造,以便每10秒重复一次我计划的操作吗?
发布于 2020-07-04 17:21:43
Applicative[F].pure不会延迟效果。它只将一个纯值提升到F中。既然你有一个Async上下文限制,我建议你使用Async[F].delay(println("tick"))。
您可以很容易地像这样递归地调用它:
def schedule[F[_]: Async: Timer]: F[Unit]
def repeat[F[_]: Async: Timer]: F[Unit] =
schedule >> repeat发布于 2021-06-24 20:46:09
只需使用上面的代码来编写完整的示例。归功于他们。
package com.example.timerapp
import cats.Applicative
import cats.effect.{Async, ExitCode, IO, IOApp, Timer}
import cats.syntax.apply._
import cats.syntax.flatMap._
import scala.concurrent.duration._
import java.time.Instant
object TimerApp extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
repeat[IO].as(ExitCode.Success)
}
def schedule[F[_]: Applicative: Async: Timer]: F[Unit] =
Timer[F].sleep(1 second) *> {
Async[F].delay(println(Instant.now.toString))
}
def repeat[F[_]: Async: Timer]: F[Unit] =
schedule[F] >> repeat
}https://stackoverflow.com/questions/62725929
复制相似问题