Exit e-book
Show all chapters
07
How to create ZLayers
07. 
How to create ZLayers

Sign up to our Newsletter

Signing up to our newsletter allows you to read all our ebooks.

I agree to receive marketing communication from Scalac.
You can unsubscribe from these communications at any time. For more information on how to unsubscribe, view our Privacy Policy.

Mastering Modularity in ZIO with Zlayer
07

How to create ZLayers

There are several ways to create instances of ZLayer:

  • ZLayer.succeed: Allows to create a ZLayer from a Service. This is useful when you want to define a ZLayer whose creation doesn’t depend on anything and doesn’t fail (meaning, it allows you to create a ULayer).
  • ZLayer.fail: Allows to build a ZLayer that always fails to build an output.
  • ZLayer.fromEffect: Allows to lift a ZIO effect to a ZLayer. This is especially handy when you want to define a ZLayer whose creation depends on an environment and/or can fail. You can also use the equivalent operator in the ZIO data type: ZIO#toLayer.
  • ZLayer.fromFunction: Allows to create a ZLayer from a function whose input is an environment and whose output is a Service. You can use this when you want to define a ZLayer whose creation depends on an environment but can’t fail (meaning, it allows you to create a URLayer).
  • ZLayer.fromManaged: Allows to lift a ZManaged effect to a ZLayer. This is applicable when you want to define a ZLayer whose creation depends on an environment and/or can fail, and when you want additional resource safety. You can also use the equivalent operator in the ZManaged data type: ZManaged#toLayer.
  • ZLayer.fromAcquireRelease: This is very similar to ZLayer.fromManaged, but it expects a ZIO effect and a release function instead.
  • ZLayer.fromService: Allows to create a ZLayer from a function whose input is a Service and whose output is another Service. This is useful when you want to define a ZLayer whose creation depends on another Service but can’t fail (meaning, it allows you to create a URLayer).
  • ZLayer.fromServices: This is similar to ZLayer.fromService, but it allows to create a ZLayer from a function whose inputs are several Services, rather than just one Service.
  • ZLayer.requires: This is used to express the requirement for a layer. Also, this is equivalent to ZLayer.identity.

As mentioned in the ZIO documentation, these methods include variants to build ZLayers effectfully (variants suffixed by M), resourcefully (variants suffixed by Managed), or to create combinations of services (suffixed by Many).

If this sounds too abstract for you now, don’t worry because we are going to use all of the above ways to create instances of ZLayer in our Tic-Tac-Toe example.

PREVIOUS
Chapter
06
NEXT
Chapter
08