Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import zio._
- trait Dependency1
- trait Dependency2
- trait Module1 {
- // It's quite common for dependencies to depend on some resources,
- // so I put them in managed even for illustrating purposes
- def dependency1: Managed[Nothing, Dependency1]
- }
- trait Module2 {
- def dependency2: Managed[Nothing, Dependency2]
- }
- // The service interface doesn't know anything about Module1 or Module2
- trait Service {
- def foo: Task[Int]
- }
- // Only the service module references the modules it depends on
- trait ServiceModule {
- def service: ZManaged[Module1 with Module2, Nothing, Service]
- }
- // The actual implementation contains its dependencies as normal parameters
- class LiveService private (dependency1: Dependency1, dependency2: Dependency2) extends Service {
- def foo = ???
- }
- // The companion object contains a factory method that uses the ZIO environment
- // to extract dependencies needed for our LiveService
- object LiveService {
- def make: ZManaged[Module1 with Module2, Nothing, Service] =
- for {
- deps <- ZIO.access[Module1 with Module2](identity).toManaged_
- dep1 <- deps.dependency1
- dep2 <- deps.dependency2
- } yield new LiveService(dep1, dep2)
- }
- object ServiceModule {
- // A live environment can now be trivially implemented on top of what we have so far
- trait Live extends ServiceModule {
- def service = LiveService.make
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement