有一个使用 ZIO 效果返回None
或的简单 API 示例Option[String]
。我使用 ZIO Schedule 来运行效果,只要None
返回,但仅限于一定次数。该示例基于ZIO usecases_scheduling中的代码:
import zio._
import zio.random._
import zio.duration._
import zio.console.{Console, putStrLn}
import zio.Schedule
import scala.util.{Random => ScalaUtilRandom}
object RecordAPI {
def randomId(length: Int): String =
LazyList.continually(ScalaUtilRandom.nextPrintableChar).filter(_.isLetterOrDigit).take(length).mkString
def getRecordId: Task[Option[String]] = Task.effect(
if (ScalaUtilRandom.nextInt(10) >= 7) Some(randomId(16)) else None
)
}
object ScheduleUtil {
def schedule[A]: Schedule[Random, Option[String], Option[String]] =
(Schedule.exponential(10.milliseconds) && Schedule.recurs(10)) *> Schedule.recurWhile(_.isEmpty)
}
object RandomScheduler extends scala.App {
implicit val rt: Runtime[zio.ZEnv] = Runtime.default
rt.unsafeRun {
RecordAPI.getRecordId
.repeat(ScheduleUtil.schedule)
.foldM(
ex => putStrLn(s"failed with ${ex.getMessage}"),
success => putStrLn(s"Succeeded with $success")
)
}
}
下面的这种效果具有以下类型ZIO[Random with clock.Clock, Throwable, Option[String]]
:
RecordAPI.getRecordId.repeat(ScheduleUtil.schedule)
我想通过提供环境来消除对的ScheduleUtil.schedule
依赖并获得效果:Random
Random
ZIO[Any with clock.Clock, Throwable, Option[String]]
RecordAPI.getRecordId.repeat(ScheduleUtil.schedule.provide(Random))
但我得到编译错误:
[error] found : zio.random.Random.type
[error] required: zio.random.Random
[error] (which expands to) zio.Has[zio.random.Random.Service]
[error] .repeat(ScheduleUtil.schedule.provide(Random))
[error] ^
[error] one error found
应该为.provide
方法提供什么参数?