ZIO

Using ZIO's Ref to ensure a singleton in the Environment

Posted on by  
Chiel van de Steeg

In a previous post I’ve shown how to use ZIO environments to provide your program with dependencies, or modules. While using environments at the customer I’m currently working for, we found out that the logic to get a database session object using a module would run over and again. This makes sense, since a ZIO[R, E, A] is a prescribed way of getting an A, and the result is not cached. Our application was reading configuration files and creating SQL sessions on every module call, while the resulting object was obviously constructed from the same underlying values. There are multiple ways to solve this:

  • Creating the singleton objects before running you application logic.

  • Caching the result of the loading code in a reference.

In this post I’ve chosen the latter, because I wanted to show the use of ZIO’s Ref. Also, I like how semantically the desired data and the logic of retrieving it belong together.

Continue reading →

Functional dependency injection in Scala using ZIO environments

Posted on by  
Chiel van de Steeg

ZIO is a type-safe, composable library for asynchronous and concurrent programming in Scala (from: The ZIO github). The library copes with functional IO, like many Functional Programming libraries do. The added value of ZIO is that the ZIO[R, E, A] type-constructor (the main IO monad of the library) acts as an IO monad, an error handling monad, and a reader monad. A functional programming style often needs a combination of these three types to cope with the most common problems when creating an application:

  • performing side effects (getting the A)

  • coping with errors (handling E)

  • supplying dependencies (providing R)

This blogpost will show you how to cope with the R part of a ZIO[R, E, A]: the Environment

Continue reading →

shadow-left