Ingress to the Monix-Eval: Task

Reading Time: 2 minutes

Monix that is used for composing Asynchronous programs for Scala and Scala.js runs on JVM. Monix 2.0 is modular by design so you can pick and choose:

  • Monix-Execution: Scheduler, Cancelable, CancelableFuture and Atomic.
  • Monix-Eval:  For controlling evaluation by means of Task, Coeval and TaskApp.
  • Monix-Reactive:  Observable.
  • Monix: Provides all of the above

Let’s first talk about what evaluation mean in scala.

Evaluation in Scala can be done in two ways:

  • Eager  –  Eager means whether you need the result or not it just evaluated before you need them.
  • Lazy– Lazy means result of an expression is evaluated on a need basis.

Above Eager and Lazy evaluation in scala are synchronous.

For Asynchronous we have:

  • Future – Future represents value, detached to time.
  • Task– Task has to do tricks in order to be “cancelable“, a trait that allows it to close opened resources when race conditions happen.

Below is an example that shows the difference between Scala Future and Monix Task:-

Task doesn’t trigger any effect until runAsync. It allows canceling the running computation.

// In order to evaluate tasks, we’ll need a Schedule

Simple Builders

//Strict evaluation

//Lazy/memoized evaluation

//Equivalent to Function

//Builds a factory of tasks

//Guarantees asynchronous execution

Memoization:
You can take any task and memoize it means it executes once and you can get the result for subsequent evaluations. If you have side effect that it would be evaluated only once.

Future memoized by default but in Task if you want memoization you need to specify it explicitly.

Tail Recursive Loops Example:-

You can describe it using Task. You use Task.defer to transform it to a lazy evaluation and Task.now to get the result.

We can use flatmap in place of defer that describes recursivity.

References: Monix Official Documentation
Thanks For Reading!! Happy Coding 🙂
monix

Written by 

Charmy is a Software Consultant having experience of more than 1.5 years. She is familiar with Object Oriented Programming Paradigms and has familiarity with Technical languages such as Scala, Lagom, Java, Apache Solr, Apache Spark, Apache Kafka, Apigee. She is always eager to learn new concepts in order to expand her horizon. Her hobbies include playing guitar and Sketching.