scala 我应该如何正确 Package 这段代码以使用猫效应3?我应该使用资源吗?

7uhlpewt  于 2023-03-04  发布在  Scala
关注(0)|答案(1)|浏览(121)

下面的代码是正确的工作与猫的影响和IO?
如果这是使用资源,如果是,有人能帮助我,因为我没有使用过资源之前。

object AWS {
  val client = AWSClientBuilder.defaultClient()

  def blah(...): IO[Unit] = IO {
     client.submitJob(new AwsRequest(....))
  }
}
goqiplq2

goqiplq21#

从技术上讲不是,因为client(以及AWS) 是共享的可变状态。
但是,重构不仅使用Resource,而且不使用全局对象,也不显式地向下传递依赖关系。
就像这样:

// Make AWS an interface that defines the operations it provides.
trait AWS {
  def foo(...): IO[Unit]
}

// In the companion object put a factory method that instantiates the resources.
object AWS {
  def instance(...): Resource[IO, AWS] =
    Resource
      .make(IO(AWSClientBuilder.defaultClient))(client => IO(client.close()))
      .map(client => new AWSImpl(client))
}

// Have a private implementation of the interface.
private[pckg] final class AWSImpl (client: AWSClient) extends AWS {
  def blah(...): IO[Unit] = IO {
    client.submitJob(new AwsRequest(...))
  }
}

// Whatever was using AWS globally before now must require its dependency.
final class Domain(aws: Aws) {
  def bar(...): IO[Unit] =
    aws.foo(...)
}

// Assembly the dependency graph on the main.
final class Main extends IOApp.Simple {
  override final val run: IO[Unit] =
    Aws.instance(...).use { aws =>
      val domain = new Domain(aws)
      domain.bar(...)
    }
}

这是一个很笼统的想法,不要盲从。

相关问题