下面的代码是否适用于猫效应和 IO?
这是否应该使用资源,如果是这样,有人可以帮助我,因为我以前没有使用过资源。
object AWS {
val client = AWSClientBuilder.defaultClient()
def blah(...): IO[Unit] = IO {
client.submitJob(new AwsRequest(....))
}
}
技术上不是,因为
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(...)
}
}
这是一个很笼统的想法,不要盲目跟风