Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/12f53a80c60e419855dd04d14adf2551 to your computer and use it in GitHub Desktop.
Save dacr/12f53a80c60e419855dd04d14adf2551 to your computer and use it in GitHub Desktop.
ZIO learning - structured services - the basic pattern / published by https://github.com/dacr/code-examples-manager #4ea028bc-f9f8-4c18-a0f9-42684a733dde/edcad95ed27eda8743b791adc2f6cc2092a23373
// summary : ZIO learning - structured services - the basic pattern
// keywords : scala, zio, learning, services, pure-functional, @testable
// publish : gist
// authors : Rock the JVM
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 4ea028bc-f9f8-4c18-a0f9-42684a733dde
// created-on : 2021-05-03T18:04:46+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// Highly inspired from Structuring Services in Scala with ZIO and ZLayer : https://www.youtube.com/watch?v=PaogLRrYo64
// And lately updated or Scala3 & ZIO2
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
// ---------------------
import zio.*
// ----------------------------------------------------------------------------------------
case class User(name: String, email: String)
// ----------------------------------------------------------------------------------------
// This is the classical service pattern used within ZIO, with the standard naming scheme
// Service definition
trait UserEmailer:
def notify(user: User, message: String): Task[Unit]
object UserEmailer:
class UserEmailerImpl() extends UserEmailer:
override def notify(user: User, message: String): Task[Unit] =
ZIO.attempt(println(s"[User emailer] Sending '$message' to ${user.email}'"))
val live: URLayer[Any, UserEmailer] = ZLayer.succeed(UserEmailerImpl())
// Front-facing API - helper function
def notify(user: User, message: String): RIO[UserEmailer, Unit] =
ZIO.serviceWithZIO(_.notify(user, message))
// ----------------------------------------------------------------------------------------
object Encapsulated extends ZIOAppDefault:
val david = User("david", "myemail@gmail.com")
val message = "Welcome to this site !"
val logic =
UserEmailer
.notify(david, message) // the kind of effect
.provideLayer(UserEmailer.live) // provide the input for that effect
override def run = logic.exitCode
Encapsulated.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment