-
Notifications
You must be signed in to change notification settings - Fork 13
/
ZIOMonad.scala
424 lines (353 loc) · 14.3 KB
/
ZIOMonad.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package app.impl.zio
import org.junit.Test
import scalaz.zio.{DefaultRuntime, IO, Task, ZIO}
import scala.concurrent.Future
import scala.util.Try
class ZIOMonad {
val main: DefaultRuntime = new DefaultRuntime {}
//##########################//
// CREATION //
//##########################//
/**
* Using ZIO we can define like the monad IO from Haskell, the monad by definition it's lazy,
* which means it respect the monad laws and it's referential transparency. Only when it's evaluated
* using [runtime.unsafeRun(monad)] it's been we move from the pure functional realm and we go into the
* effect world.
* In order to control effects this monad has 3 types defined.
* * R - Environment Type. This is the type of environment required by the effect. An effect that
* * has no requirements can use Any for the type parameter.
* * E - Failure Type. This is the type of value the effect may fail with. Some applications will
* * use Throwable. A type of Nothing indicates the effect cannot fail.
* * A - Success Type. This is the type of value the effect may succeed with. This type parameter
* * will depend on the specific effect, but Unit can be used for effects that do not produce any useful information, while Nothing can be used for effects that run forever.
*/
@Test
def fromZIOSucceed(): Unit = {
val sentenceMonad: ZIO[Any, Throwable, String] =
ZIO
.succeed("Hello pure functional wold")
.map(value => value.toUpperCase())
.flatMap(word => ZIO.succeed(word + "!!!"))
val succeedSentence = main.unsafeRun(sentenceMonad)
println(succeedSentence)
}
/**
* Using Task monad, we can no control effects since only contemplate one possible type.
*/
@Test
def fromTaskSucceed(): Unit = {
val task: Task[String] =
Task
.succeed("Hello pure functional ")
.flatMap(sentence => Task.succeed(sentence + " world"))
.map(sentence => sentence.toUpperCase())
val taskSentence = main.unsafeRun(task)
println(taskSentence)
}
/**
* We describe before that using IO monad the evaluation of the monad it's lazy. And it's true
* but what it's not lazy evaluation it's the input value of the monad, in order to do have also
* a lazy evaluation of that value, you need to use operator [succeedLazy] it will behave just like
* Observable.defer of RxJava
*/
@Test
def fromZIOLazy(): Unit = {
val lazyIputMonad = ZIO.succeedLazy(s"Monad___ ${System.currentTimeMillis()}")
Thread.sleep(1000)
println("No Monad " + System.currentTimeMillis())
val lazySentence = main.unsafeRun(lazyIputMonad)
println(lazySentence)
}
/**
* Also we can create a monad IO with a failure that some errors were not
* controlled properly
*/
@Test
def fromZIOFailure(): Unit = {
val errorMonad: IO[String, Throwable] =
ZIO.fail("Hello pure functional wold")
main.unsafeRun(errorMonad)
}
/**
* Also we can create a monad IO with a throwable propagation, expressions that some errors were not
* controlled properly
*/
@Test
def fromZIOThrowable(): Unit = {
val errorMonad1: IO[Exception, Nothing] =
ZIO.fail(new IllegalArgumentException("Hello pure functional wold"))
main.unsafeRun(errorMonad1)
}
//##########################//
// EFFECTS //
//##########################//
/**
* In case we want to create a IO from an option effect, we use [fromOption] operator.
* In order to get the effect to None we use the operator [catchAll] which in case
* of None it will invoke the function with unit type.
*/
@Test
def optionZIO(): Unit = {
val monadSome: ZIO[Any, Unit, String] =
ZIO.fromOption(Some("Hello"))
.catchAll(unit => ZIO.succeed(s"No data in Option"))
.flatMap(word => ZIO.succeed(word + " maybe"))
.map(sentence => sentence.toUpperCase)
val value = main.unsafeRun(monadSome)
println(value)
val monadNone =
ZIO.fromOption(maybe())
.catchAll(unit => ZIO.succeed(s"No data in Option"))
.map(sentence => sentence.toUpperCase)
val none = main.unsafeRun(monadNone)
println(none)
}
/**
* In case we want to create a IO from an Try effect, we use [fromTry] operator.
* In order to get the effect to Value or Throwable we use the operator [catchAll] which in case
* of Try Failure it will invoke the function with the Throwable type.
*/
@Test
def tryZIO(): Unit = {
val trySuccess =
ZIO.fromTry(Try(1981))
.map(number => number + 100)
.catchAll(t => ZIO.succeed(s"I catch an error from Try $t"))
val goodValue = main.unsafeRun(trySuccess)
println(goodValue)
val tryError =
ZIO.fromTry(Try(42 / 0))
.map(number => number + 100)
.catchAll(t => ZIO.succeed(s"I catch an error from Try $t"))
val value = main.unsafeRun(tryError)
println(value)
}
/**
* In case we want to create a IO from an Either effect, we use [fromEither] operator.
* In order to get the effect of Left or Right type, we use the operator [catchAll] which in case
* of Either Left it will invoke the function with the Left type defined in Either.
*/
@Test
def eitherZIO(): Unit = {
val rightMonad: ZIO[Any, Int, String] =
ZIO.fromEither(rightValue())
.map(sentence => sentence + " !!!")
.map(sentence => sentence.toUpperCase)
.catchAll(leftSide => ZIO.succeed(s"I catch the left side of the either $leftSide"))
val value = main.unsafeRun(rightMonad)
println(value)
val leftMonad: ZIO[Any, Int, String] =
ZIO.fromEither(eitherValue())
.map(sentence => sentence + " !!!")
.map(sentence => sentence.toUpperCase)
.catchAll(leftSide => ZIO.succeed(s"I catch the left side of the either $leftSide"))
val leftValue = main.unsafeRun(leftMonad)
println(leftValue)
}
/**
* In case we want to create a IO from a Future execution, we use [fromFuture] operator.
* ZIO provide the option to zip the futures and just like Scala future zip it return a Tuple
* of the results.
*/
@Test
def futureZIO(): Unit = {
val monadFuture: Task[String] =
ZIO.fromFuture { implicit ec =>
Future("I'll see you in the future")
}
.zip(ZIO.fromFuture({ implicit ec =>
Future(", for sure!")
}))
.map(sentence => (sentence._1 + sentence._2).toUpperCase)
val value = main.unsafeRun(monadFuture)
println(value)
}
//##########################//
// PROGRAM //
//##########################//
/**
* Main program that compose all ZIO monads created with effects.
* To be more Haskell style we use for comprehension emulating the
* [do block] style of Haskell
*/
@Test
def mainProgramWithEffects(): Unit = {
val userMonad = for {
user <- login("politrons")
user <- updateAge(user)
user <- findUserAsEmployee(user)
user <- persistEmployeeInDataBase(user)
} yield user
val value = main.unsafeRun(userMonad)
println(value)
}
def login(username: String): ZIO[Any, Throwable, User] =
ZIO.fromOption(Some(User("politrons", 38)))
.catchAll(unit => ZIO.succeed(User("No user", 0)))
def updateAge(user: User): ZIO[Any, Throwable, User] =
ZIO.fromTry(Try(user.copy(age = user.age + 1)))
def findUserAsEmployee(user: User): ZIO[Any, Throwable, User] =
ZIO.fromEither(Right(user))
def persistEmployeeInDataBase(user: User): ZIO[Any, Throwable, User] =
ZIO.fromFuture {
implicit ec => Future(user)
}
def maybe(): Option[String] = None
def eitherValue(): Either[Int, String] = Left(100)
def rightValue(): Either[Int, String] = Right("This monad was Success!")
case class User(name: String, age: Int)
//##########################//
// ENVIRONMENT //
//##########################//
/**
* Just like Monad Reader, we can use a environment type, that can be used internally in your program.
* This is really handy when you want to have different values per environment, or you just want
* to apply Module pattern to make your DSL completely abstract of the implementation passed per environment.
*
* In order to access to the whole environment type you just need to use [environment] operator and you will receive the instance
* of the type
*
* If you just want access some part of the environment, you just need to use [access] operator, which it's
* a function that pass the environment type, so you can access to the functions that the env type provide.
*
* Once you evaluate your program you need to pass the implementation of the environment using [provide] operator.
*/
@Test
def environmentType(): Unit = {
val userMonad: ZIO[User, Nothing, String] =
for {
user <- ZIO.environment[User]
name <- ZIO.access[User](env => env.name)
age <- ZIO.access[User](_.age)
} yield s"Before User Name: ${user.name}, age: ${user.age}. After Name: ${name.toUpperCase()}, age: ${age + 1}"
val info = main.unsafeRun(userMonad.provide(User("Politrons", 38)))
println(info)
}
/**
* Using the environment we're able to use a pipeline, extracting the monads from environment type
* allowing polymorphism in the implementation of that environment.
*
* Here [CustomLogic] it's a trait that have two implementations, one for DEV environment and another
* for production environment. Using the [accessM] operator we can extract the value from the monad
* from the implementations of the trait function, in PROD env it will return something different from
* the DEV env, but our for comprehension remain the same without have to being refactor.
*/
@Test
def environmentModulePattern(): Unit = {
val userMonad: ZIO[CustomLogic, Nothing, String] =
for {
server <- ZIO.accessM[CustomLogic](env => env.getAddress)
port <- ZIO.accessM[CustomLogic](_.getPort)
} yield s"Server: $server, port: $port"
val devInfo = main.unsafeRun(userMonad.provide(CustomDevLogic))
println(devInfo)
val realInfo = main.unsafeRun(userMonad.provide(CustomLiveLogic))
println(realInfo)
}
/**
* Define here the environment type to be implemented pèr real case and some test cases.
* Or even multiple programs.
*/
trait CustomLogic {
def getAddress: ZIO[Any, Nothing, String]
def getPort: ZIO[Any, Nothing, Int]
}
/**
* Implementation of the environment type to be used for DEV. It could be used to test some behavior and
* corner cases in testing.
*/
object CustomDevLogic extends CustomLogic {
override def getAddress: ZIO[Any, Nothing, String] = ZIO.succeed("Dev socket address")
override def getPort: ZIO[Any, Nothing, Int] = ZIO.succeed(666)
}
/**
* Implementation of the environment type to be used for LIVE version.
*/
object CustomLiveLogic extends CustomLogic {
override def getAddress: ZIO[Any, Nothing, String] = ZIO.succeed("Real socket address")
override def getPort: ZIO[Any, Nothing, Int] = ZIO.succeed(1981)
}
@Test
def foreachZIO(): Unit = {
val strings = main.unsafeRun((for {
xx <- ZIO.foreach(List[String]("hello", "zio", "world"))(value => {
ZIO.effect(value.toUpperCase)
})
} yield xx).catchAll(t => ZIO.succeed(List(t.getMessage))))
println(strings)
}
@Test
def foreachZIOWithError(): Unit = {
val strings = main.unsafeRun((for {
xx <- ZIO.foreach(List[String]("hello", null, "world"))(value => {
ZIO.effect(value.toUpperCase)
})
} yield xx).catchAll(t => ZIO.succeed(List("Some effect might happens"))))
println(strings)
}
@Test
def zioWhen(): Unit = {
main.unsafeRun((for {
_ <- ZIO.when(true)(ZIO.effect(println("Hello if condition")))
} yield ()).catchAll(_ => ZIO.succeed("Else condition here")))
main.unsafeRun(for {
_ <- ZIO.when(false)(ZIO.effect(println("Hello if condition")))
} yield ())
main.unsafeRun(for {
_ <- ZIO.whenM(ZIO.effect(true))(ZIO.effect(println("Hello if effect condition")))
} yield ())
}
@Test
def zioParallel(): Unit = {
main.unsafeRun((for {
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} Hello")).fork
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} Async")).fork
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO")).fork
} yield ()).catchAll(_ => ZIO.succeed(println("Control async effects"))))
}
@Test
def zioParallelZip(): Unit = {
main.unsafeRun(for {
f1 <- ZIO.effect(println(s"${Thread.currentThread().getName} Hello")).fork
f2 <- ZIO.effect(println(s"${Thread.currentThread().getName} Async")).fork
f3 <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO")).fork
_ <- (f1 zip f2 zip f3).join
} yield ())
}
@Test
def zioParallelZipError(): Unit = {
main.unsafeRun((for {
f1 <- ZIO.effect(println(s"${Thread.currentThread().getName} Hello")).fork
f2 <- ZIO.effect(throw new NullPointerException).fork
f3 <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO")).fork
_ <- (f1 zip f2 zip f3).join
} yield ()).catchAll(_ => ZIO.succeed(println("Control async effects"))))
}
@Test
def zioParallelError(): Unit = {
main.unsafeRun((for {
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} Hello")).fork
_ <- ZIO.effect(throw new NullPointerException).fork
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO")).fork
} yield ()).catchAll(_ => ZIO.succeed(println("Control async effects"))))
}
@Test
def zioError(): Unit = {
main.unsafeRun((for {
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} Hello"))
_ <- ZIO.effect(throw new NullPointerException)
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO"))
} yield ()).catchAll(_ => ZIO.succeed(println("Control async effects"))))
}
@Test
def zioErrorWhen(): Unit = {
main.unsafeRun((for {
_ <- ZIO.when(false)(
for {
_ <- ZIO.effectTotal(println("Why this happens?"))
_ <- ZIO.fail(new IllegalArgumentException())
} yield ())
_ <- ZIO.effect(println(s"${Thread.currentThread().getName} ZIO"))
} yield ()).catchAll(_ => ZIO.succeed(println("Control async effects"))))
}
}