JavaScript

通过将以下内容添加到您的 build.sbt 中,使得在 Scala.js 项目中支持 ZIO:

scalaJSUseMainModuleInitializer := true
libraryDependencies += "dev.zio" %%% "zio" % "1.0.1"

例子

您的 main 函数可以像下面这样通过扩展 App 得到。这个例子使用 scala-js-dom 来访问 DOM;要运行该示例,您将需要将该库作为依赖项添加到 build.sbt中。

import org.scalajs.dom.{document, raw}
import zio._
import zio.duration._
import zio.clock._

object Main extends App {

  def run(args: List[String]) = {
    for {
      _      <- putStrLn("Starting progress bar demo.")  // Outputs on browser console log.
      target <- IO.effectTotal(document.createElement("pre"))
      _      <- update(target).repeat(Schedule.spaced(1.seconds))
      _      <- IO.effectTotal(node.appendChild(target)) // "node" is provided in this page by mdoc.
    } yield ExitCode.success
  }

  def update(target: raw.Element) = {
      for {
        time   <- currentTime(TimeUnit.SECONDS)
        output <- UIO.effectTotal(progress((time % 11).toInt, 10))
        _      <- UIO.effectTotal(target.innerHTML = output)
      } yield ()
  }

  def progress(tick: Int, size: Int) = {
      val bar_length = tick
      val empty_length = size - tick
      val bar = "#" * bar_length + " " * empty_length
      s"$bar $bar_length%"
  }

}
Leave a Reply
Your email address will not be published.
*
*

BACK TO TOP