I'm a little confused as to when you would use `IO...
# arrow
c
I'm a little confused as to when you would use
IO.fx
and when you would just use
IO
s
IO.fx
is just a DSL to write
IO
without having to rely on
flatMap
. Additionally it tries to improve the syntax wherever possible, based on the tricks we can apply in the DSL 🙂
c
Would it be accurate to say that `fx`blocks in general (not just for IO) are a way to write operations based on flatMap with a ‘more natural' sequential syntax?
💯 4
s
That’s absolutely correct 🙂
r
Fx is the equivalent in Haskell to do notation and in Scala to for comprehensions, or python generators. That is a computational context where you are inside the Monad you are computing and therefore its operator for map or flatMap etc make no sense since all syntax up to Monad is swallowed in the block so you can use it as sequential imperative commands. A lot of people are frequently misslead that Imperative and FP are the oposite styles and that is not the case. Imperative FP is possible because of the effect tracking suspend and restrict suspension does.
c
I apologize for what feels like a dumb follow-up question (I am brand new to FP concepts), but what exactly do you mean by this?
IO.fx
is just a DSL to write
IO
without having to rely on
flatMap
.
In the Getting Started docs, there's an example provided where two side effects are composed inside of an
fx
object. Is
flatMap
being used here in some way?
Copy code
suspend fun sayHello = println(...)
suspend fun sayGoodbye = println(...)
fun greet(): IO<Unit> =
    IO.fx {
        !effect { sayHello() }
        !effect { sayGoodbye() }
    }
c
I'm new to these concepts myself, so this might not be accurate, but I think he meant this syntax:
Copy code
SomeMonad.fx {
  val (a) = something()
  val (b) = somethingElse(a)
}
which, if I understand correctly, is syntax sugar for:
val b = something().flatMap { somethingElse(it) }
💯 1
s
@Chris Cordero like @CLOVIS mentioned, it’s syntactic sugar for
flatMap
. It uses
suspend
and
Continuation
underneath to delegate to
flatMap
.
c
Even for the example I gave? In @CLOVIS’s example, the
somethingElse
needed to use the value of
a
but in my example the two effects were completely independent of each other.
s
Yes, it’s rewritten to
effect { sayHello() }.flatMap { effect { sayGoodbye() } }
. If you were to change
IO.fx
to
Concurrent.fx
you can also re-use the same program from
RxJava
or
Reactor
.