2

假设我在使用无标记Cats-effect最终方法的项目中有以下方法签名:

def schedule[F[_]: Applicative : Async: Timer]

我正在尝试schedule使用纯 FP 对方法调用安排操作。

我试过这样:

Timer[F].sleep(FiniteDuration(10, TimeUnit.SECONDS)) *> {
    Applicative[F].pure(println("tick"))
}

但它没有用,因为效果 println("tick")Timer初始化阶段执行。

我怎样才能让它正常工作?

我还可以创建某种递归构造,以便每 10 秒重复一次我的预定操作吗?

4

2 回答 2

4

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
于 2020-07-04T09:21:43.293 回答
0

只是用上面写了一个完整的例子。归功于他们。

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

}

于 2021-06-24T12:46:09.477 回答