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/f8f284a27ea4f0e24e357a7ad5de3c3c to your computer and use it in GitHub Desktop.
Save dacr/f8f284a27ea4f0e24e357a7ad5de3c3c to your computer and use it in GitHub Desktop.
ZIO learning - quick layer definition / published by https://github.com/dacr/code-examples-manager #0abcfad6-eb23-4b36-86c9-9d5efcbcd5e7/773fa80f03371382be710f17bb9dcaee301bd785
{"timestamp": "2022-03-04T11:25:50Z", "value": 41.0}
{"timestamp": "2022-03-04T11:26:17Z", "value": 42.0}
{"timestamp": "2022-03-04T11:26:42Z", "value": 42.0}
// summary : ZIO learning - quick layer definition
// keywords : scala, zio, layers, to-layer, nio, json, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 0abcfad6-eb23-4b36-86c9-9d5efcbcd5e7
// attachments : zio-learning-31-layers-1.json
// created-on : 2022-03-04T11:20:53+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "dev.zio::zio-nio:2.0.1"
//> using dep "dev.zio::zio-json:0.5.0"
// ---------------------
/*
Inspired from https://www.youtube.com/watch?v=PJTn33Qj1nc&ab_channel=Ziverge
*/
import zio.*
import zio.json.*
import zio.nio.file.*
import java.time.Instant
case class Sample(timestamp: Instant, value: Double)
object Sample:
implicit val codec: JsonCodec[Sample] = DeriveJsonCodec.gen
case class Samples(temperatureSamples: Seq[Sample])
object Encapsulated extends ZIOAppDefault:
val samples = ZLayer(
for
lines <- Files.readAllLines(Path("zio-learning-31-layers-1.json"))
samples <- ZIO.foreach(lines)(line => ZIO.fromEither(line.fromJson[Sample]))
yield Samples(samples)
)
val logic =
for
samples <- ZIO.serviceWith[Samples](_.temperatureSamples)
_ <- ZIO.foreach(samples)(t => Console.printLine(t.toJson))
yield ()
override def run = logic.provideSomeLayer(samples)
Encapsulated.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment