我应该如何正确包装此代码以与 Cats Effect 3 一起使用?我应该使用资源吗?

问题描述 投票:0回答:1

下面的代码是否适用于猫效应和 IO?

这是否应该使用资源,如果是这样,有人可以帮助我,因为我以前没有使用过资源。

object AWS {
  val client = AWSClientBuilder.defaultClient()

  def blah(...): IO[Unit] = IO {
     client.submitJob(new AwsRequest(....))
  }
}
scala scala-cats cats-effect
1个回答
0
投票

技术上不是,因为

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(...)
    }
}

这是一个很笼统的想法,不要盲目跟风

© www.soinside.com 2019 - 2024. All rights reserved.