Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active April 25, 2019 13:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yasuabe/bce840929e77d54b17832c4eafeb8d8e to your computer and use it in GitHub Desktop.
dependency injection sample with ZIO
import scalaz.zio.{DefaultRuntime, IO, ZIO}
// domain layer -----------------------------------------------------------
sealed trait AppError
case object NoValue extends AppError
case class Movie(id: Int, title: String)
trait MovieRepo {
def getMovie(id: Int): IO[AppError, Movie]
}
// application layer ----------------------------------------------
val db = Map[Int, Movie](42 -> Movie(42, "A Movie"))
object MovieRepoImpl extends MovieRepo {
def getMovie(id: Int): IO[AppError, Movie] =
IO.fromEither(db.get(id).toRight(NoValue))
}
trait Env {
val movieRepo: MovieRepo
}
object Env extends Env {
val movieRepo = MovieRepoImpl
}
object MovieService {
def getMovie(id: Int): ZIO[Env, AppError, Movie] =
ZIO.environment[Env] >>= (_.movieRepo.getMovie(id))
}
val program: ZIO[Env, AppError, Movie] = MovieService.getMovie(42)
// runtime layer -------------------------------------------------
new DefaultRuntime {}.unsafeRunSync(program.provide(Env))
// testing layer -------------------------------------------------
import cats.syntax.either._
new DefaultRuntime {}.unsafeRunSync(program.provide(new Env {
val movieRepo = _ => IO.fromEither(NoValue.asLeft)
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment