Services and Layers
The R type parameter of ZIO[R, E, A] lists the services an effect needs before it can run, such as a database, a configuration, or an HTTP client. This page shows the three steps that make such a program run: define a service, build its implementation with a layer, and provide the layer to the program.
Defining a Serviceโ
A service is a trait whose methods return effects. The trait says what the service can do and hides how it does it:
import zio._
trait UserRepo {
def findName(id: Int): Task[Option[String]]
}
To use a service, ask the environment for it. ZIO.serviceWithZIO takes a function from the service to an effect, and the type of the result shows the requirement in R:
def greeting(id: Int): ZIO[UserRepo, Throwable, String] =
ZIO.serviceWithZIO[UserRepo](_.findName(id)).map {
case Some(name) => s"Hello, $name!"
case None => "Hello, stranger!"
}
greeting cannot run yet: its type says that something must first supply a UserRepo. ZIO.service[UserRepo] returns the service itself, for code that calls several of its methods.
Building Services with Layersโ
A ZLayer[RIn, E, ROut] is a recipe that builds the service ROut from the services RIn, and may fail with an E. The implementation of a service is usually a case class, with its layer in the companion object.
ZLayer.apply builds a layer from an effect that creates the service. This implementation keeps its data in a Ref, so the layer creates the Ref first:
final case class InMemoryUserRepo(users: Ref[Map[Int, String]]) extends UserRepo {
def findName(id: Int): Task[Option[String]] =
users.get.map(_.get(id))
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map(1 -> "Ada", 2 -> "Grace")).map(InMemoryUserRepo(_))
}
}
A service can depend on other services. ZLayer.fromFunction turns the constructor of a case class into a layer whose input is the constructor's parameters, so this Greeter layer needs a UserRepo:
trait Greeter {
def greet(id: Int): Task[String]
}
final case class GreeterLive(repo: UserRepo) extends Greeter {
def greet(id: Int): Task[String] =
repo.findName(id).map(name => s"Hello, ${name.getOrElse("stranger")}!")
}
object GreeterLive {
val layer: URLayer[UserRepo, Greeter] =
ZLayer.fromFunction(GreeterLive(_))
}
When a service holds a resource that must be released, such as a connection pool, build its layer with ZLayer.scoped and ZIO.acquireRelease. The resource is released when the program that uses the layer ends.
Providing Layersโ
ZIO#provide takes the layers a program needs and removes the requirements from its R type. It works out the order in which to build the layers from their types, so the order of the arguments does not matter:
object GreeterApp extends ZIOAppDefault {
val program: ZIO[Greeter, Throwable, Unit] =
ZIO.serviceWithZIO[Greeter](_.greet(1)).flatMap(Console.printLine(_))
def run =
program.provide(
GreeterLive.layer,
InMemoryUserRepo.layer
)
}
ZIO#provide checks the layers at compile time. If a layer is missing, for example if we leave out InMemoryUserRepo.layer, compilation fails with a message that names the missing UserRepo and the layer that needs it. Each layer is built once, even when several other layers depend on it.
Because the program depends only on the Greeter and UserRepo traits, a test can provide other implementations of them. Writing Tests shows how.
The Dependency Injection section covers layers in depth, and Writing ZIO Services covers how to design services.
Next Stepsโ
If you are comfortable with defining services and providing layers, the next step is to learn about writing tests.