1

我想玩 ZIO 计划和重试,但找不到完成的示例。这段代码怎么样(IDEA 中的研讨会):

import zio._
import zio.duration._
import zio.console._

val r = scala.util.Random

def funcReadFromDb(inp :Int): Task[Seq[Int]]= {
  val rnd :Int = r.nextInt(10)
  println(s"rnd=$rnd")
  //if (rnd <= 5)
    Task.succeed(Seq(inp, inp * 2, inp * 3))
  //else Task.fail(new Exception("custom exception"))
}

val spaced :zio.Schedule[zio.clock.Clock with Console,Any,Int] = Schedule.spaced(1.second)

val schedEff = for {
  s <- funcReadFromDb(3).repeat(spaced)
  _ <- putStrLn(s"s=$s")
} yield ()

val runtime = new DefaultRuntime {}
runtime.unsafeRun(schedEff)

我期望一些以 1 秒为间隔的迭代输出。并有输出:

spaced: zio.Schedule[zio.clock.Clock with zio.console.Console,Any,Int] = zio.Schedule$$anon$18@535bf6e0

rnd=4
schedEff: zio.ZIO[zio.clock.Clock with zio.console.Console,Throwable,Unit] = zio.ZIO$FlatMap@63303dbf

runtime: zio.DefaultRuntime = $anon$1@3e661711
4

1 回答 1

4

funcReadFromDb不纯。nextInt并且println是效果,必须包裹在Task身体中。

def funcReadFromDb(inp :Int): Task[Seq[Int]]= {
    Task.effect {
      val rnd: Int = r.nextInt(10)
      println(s"rnd=$rnd")
      Seq(inp, inp * 2, inp * 3)
    }
}
于 2019-11-22T09:31:07.487 回答