None
またはを返すために ZIO 効果を使用する単純な 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
か?