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-Eval: For controlling evaluation by means of
- Monix: Provides all of the above
Before we start learning Monix Tasks. 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
//Equivalent to Function
//Builds a factory of tasks
//Guarantees asynchronous execution
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 🙂