Skip to content

Instantly share code, notes, and snippets.

@alexandredantas
Last active July 22, 2019 21:10
Show Gist options
  • Save alexandredantas/6d09f02ec81db4aac5ecf0d482ff4613 to your computer and use it in GitHub Desktop.
Save alexandredantas/6d09f02ec81db4aac5ecf0d482ff4613 to your computer and use it in GitHub Desktop.
Setting up ZIO environment with custom traits
import zio.clock.Clock
import zio.console.Console
import zio.system.System
import zio.random.Random
import zio.blocking.Blocking
import com.typesafe.config.Config
import zio.Task
import com.typesafe.config.ConfigFactory
import scala.collection.JavaConverters
trait Configuration extends Serializable {
val config: Configuration.Service
}
object Configuration {
trait Service {
val load: Task[Config]
}
}
trait Live extends Configuration {
val config: Service = new Service {
val load: Task[Config] = Task
.effect(ConfigFactory.load())
.map(cfg => {
cfg.checkValid(ConfigFactory.parseMap(JavaConverters.mapAsJavaMap(defaultConfig)))
cfg
})
.orDie
}
}
object App extends zio.App{
override type Environment = Clock with Console with System with Random with Blocking with Configuration
private lazy val appEnvironment = new Clock.Live with Console.Live with System.Live with Random.Live with Blocking.Live with Live
override def run(args: List[String]): ZIO[Environment, Nothing, Int] = {
val program = for{
cfg <- ZIO.accessM[Environment](_.config.load)
... //other instructions
} yield cfg
program
.provide(appEnvironment)
.catchAll(e => IO.fail(e))
.run
.map{
case f => f match {
case Exit.Failure(error) => {
error.defects.foreach(_.printStackTrace())
1
}
case Exit.Success(_) => 0
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment