Skip to content

Commit

Permalink
implement ZLayer#project (zio#4123)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgfraser authored Aug 21, 2020
1 parent 4f50e71 commit 95237d0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions core-tests/shared/src/test/scala/zio/ZLayerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,12 @@ object ZLayerSpec extends ZIOBaseSpec {
val layer4 = ZLayer.fromAcquireRelease(sleep)(_ => sleep)
val env = layer1 ++ ((layer2 ++ layer3) >+> layer4)
assertM(ZIO.unit.provideCustomLayer(env).run)(fails(equalTo("foo")))
},
testM("project") {
final case class Person(name: String, age: Int)
val personLayer = ZLayer.succeed(Person("User", 42))
val ageLayer = personLayer.project(_.age)
assertM(ZIO.service[Int].provideLayer(ageLayer))(equalTo(42))
}
)
}
10 changes: 10 additions & 0 deletions core/shared/src/main/scala/zio/ZLayer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,16 @@ object ZLayer {
ZLayer.identity[RIn] ++ self
}

implicit final class ZLayerProjectOps[R, E, A](private val self: ZLayer[R, E, Has[A]]) extends AnyVal {

/**
* Projects out part of one of the layers output by this layer using the
* specified function
*/
final def project[B: Tag](f: A => B)(implicit tag: Tag[A]): ZLayer[R, E, Has[B]] =
self >>> ZLayer.fromFunction(r => f(r.get))
}

/**
* A `MemoMap` memoizes dependencies.
*/
Expand Down

0 comments on commit 95237d0

Please sign in to comment.