有一个简单API的例子,它使用ZIO效果返回None或Option[String]。我使用ZIO调度来运行效果,只要返回None,但限制在一定次数内。该示例基于来自排程的代码
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 env来消除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方法提供哪些参数?
发布于 2020-12-01 08:41:27
错误消息告诉您,您试图传递到行中的函数provide Random.type:
RecordAPI.getRecordId.repeat(ScheduleUtil.schedule.provide(Random))Random作为类型传递,但provide需要Random的实例。因此,只需将Random类型替换为它的实例,就可以使代码可编译:
val hasRandomService: Random = Has.apply(Random.Service.live)
val randomIdZIO: ZIO[Random, Throwable, Option[String]] =
RecordAPI.getRecordId.repeat(ScheduleUtil.schedule.provide(hasRandomService))但是,如果您想摆脱ScheduleUtil.schedule,最好使用Schedule.fromFunction函数:
val randomIdZIOFromFunction: ZIO[Random, Throwable, Option[String]] =
RecordAPI.getRecordId.repeat(
Schedule.fromFunction(_ => if (ScalaUtilRandom.nextInt(10) >= 7) Some(randomId(16)) else None)
)https://stackoverflow.com/questions/65080762
复制相似问题