Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. import zio._
  2.  
  3. trait Dependency1
  4. trait Dependency2
  5.  
  6. trait Module1 {
  7. // It's quite common for dependencies to depend on some resources,
  8. // so I put them in managed even for illustrating purposes
  9. def dependency1: Managed[Nothing, Dependency1]
  10. }
  11.  
  12. trait Module2 {
  13. def dependency2: Managed[Nothing, Dependency2]
  14. }
  15.  
  16. // The service interface doesn't know anything about Module1 or Module2
  17. trait Service {
  18. def foo: Task[Int]
  19. }
  20.  
  21. // Only the service module references the modules it depends on
  22. trait ServiceModule {
  23. def service: ZManaged[Module1 with Module2, Nothing, Service]
  24. }
  25.  
  26. // The actual implementation contains its dependencies as normal parameters
  27. class LiveService private (dependency1: Dependency1, dependency2: Dependency2) extends Service {
  28. def foo = ???
  29. }
  30.  
  31. // The companion object contains a factory method that uses the ZIO environment
  32. // to extract dependencies needed for our LiveService
  33. object LiveService {
  34. def make: ZManaged[Module1 with Module2, Nothing, Service] =
  35. for {
  36. deps <- ZIO.access[Module1 with Module2](identity).toManaged_
  37. dep1 <- deps.dependency1
  38. dep2 <- deps.dependency2
  39. } yield new LiveService(dep1, dep2)
  40. }
  41.  
  42. object ServiceModule {
  43. // A live environment can now be trivially implemented on top of what we have so far
  44. trait Live extends ServiceModule {
  45. def service = LiveService.make
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement