Last active
November 28, 2019 16:43
-
-
Save kellydavid/0136dade46a3d41046e748aa10b61b69 to your computer and use it in GitHub Desktop.
ZioProvideDemo.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zio._ | |
import zio.console._ | |
object ZioProvideDemo extends App { | |
trait HelloService { | |
val helloService: HelloService.Service | |
} | |
object HelloService { | |
trait Service { | |
def hello(name: String): RIO[Console, Unit] | |
} | |
} | |
trait HelloServiceLive extends HelloService { | |
val helloService: HelloService.Service = new HelloService.Service { | |
override def hello(name: String): RIO[Console, Unit] = putStrLn(s"Hello $name!") | |
} | |
} | |
def doSomeStuffDependsOnHelloService(): ZIO[HelloService with Console, Nothing, Int] = | |
(for{ | |
_ <- putStrLn("Please enter your name.") | |
name <- getStrLn | |
_ <- ZIO.environment[HelloService].flatMap(_.helloService.hello(name)) | |
} yield 0).fold(_ => 1, s => s) | |
val program: ZIO[HelloService with Console, Nothing, Int] = doSomeStuffDependsOnHelloService() | |
object HelloRuntimeLive extends HelloServiceLive with Console.Live | |
val hwRuntime: HelloService with Console = HelloRuntimeLive | |
override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, Int] = | |
program.provide(hwRuntime) *> putStrLn("Done.").map(_ => 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment