2

有一个使用 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依赖并获得效果:RandomRandomZIO[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方法提供什么参数?

4

1 回答 1

1

错误消息告诉您您尝试传递给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)
)
于 2020-12-01T08:41:27.337 回答