ZIO 和多个回调

ZIO and multiple callbacks

我对使用 ZIO 还很陌生。我目前正在用 Scala 编写一个加密货币交易机器人,同时我正在尝试学习 ZIO。现在我打开一个 websocket,这个 websocket 提供多个回调,直到它关闭,我正在努力将其集成到我的代码中。我当前的代码:

object Main extends zio.App with Logging {
   def run(args: List[String]): URIO[Any with Console, ExitCode] = Configuration.getConfiguration.fold(onError, start).exitCode

   private val interval: CandlestickInterval = CandlestickInterval.ONE_MINUTE

   private def onError(exception: ConfigurationException): ZIO[Any, Throwable, Unit]  = {
     logger.info("Could not initialize traderbot!")
     logger.error(exception.getMessage)
     IO.succeed()
   }

   private final def start(configuration: Configuration): ZIO[Any, Throwable, Unit] = {
      for {
        binanceClient <- IO.succeed(BinanceApiClientFactory.newInstance(configuration.apiKey, configuration.secret))
        webSocketClient <- IO.succeed(binanceClient.newWebSocketClient())
        candlesticks <- Task.effectAsync[CandlestickEvent] {
          callback =>
            webSocketClient.onCandlestickEvent(
            "adaeur",
            interval, d => callback(IO.succeed(d))
          )
        })
        // TODO Calculate RSI from candlesticks.
   } yield candlesticks
 }
}

我想继续接收烛台事件并保持功能正常。我看到了一些关于 Zio Streams 的东西,但是我找不到处理循环回调并且简单易懂的例子。现在我无法使用我的烛台代码来理解。

感谢您的宝贵时间!

不幸的是,ZIO 在使用 effectAsync 时无法处理多个回调,因为数据类型基于单个成功或失败值。

您可以改用 ZStream,尽管它有一个形状相似的运算符,可以多次调用:

private final def start(configuration: Configuration): ZStream[Any, Throwable, Unit] = {
  val candlesticks = ZStream.unwrap(
    IO.effectTotal {
      val client = BinanceApiClientFactory
        .newInstance(configuration.apiKey, configuration.secret)
        .newWebSocketClient()

      // This variant accepts a return value in the `Left` which 
      // is called when during shutdown to make sure that the websocket is 
      // cleaned up
      ZStream.effectAsyncInterrupt { cb => 
        val closeable = webSocketClient.onCancelstickEvent(
          "adaeur",
          interval,
          d => cb(IO.succeed(d)
        ) 

        Left(UIO(closeable.close()))
      }
  )

  for {
    candlestick <- candlesticks
    // TODO Calculate RSI from candlesticks.
  } yield ()
}