1

Is there a way to get the value inside an IO, without using unsafeRunSync() ?

For instance, I have a

val x : IO[Long] = IO$9125

I want to get the Long value in order to perform some computation on it without using unsafeRunSync()

Her sincerly
  • 373
  • 1
  • 13

2 Answers2

4

You shouldn't want to get the value from monadic context. This is incorrect way of thinking (retrieving the value from a context is typical for Comonad).

Monads in pictures.

What is a monad?

You shouldn't want to get A from Option[A], A from List[A], A from Future[A], A from IO[A]... As soon as you get into monadic calculation you should continue to work inside the monad, with .map, .flatMap, for-comprehensions etc.

For example for val x: IO[Long] = ... inside

for {
  long <- x
  ...
} yield ...

long has type Long.

So you do calculations inside IO and execute unsafeRunSync() or unsafePerformIO() once at the very end.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
4

Because IO forms a Functor you can map over it

IO(41L).map(_ + 1)

Because IO forms a Monad you can put it through a for-comprehension

for {
  a <- IO(1L)
  b <- IO(41L)
} yield a + b

Note that semantics of IO do not really mean it is a kind of container that holds a value which we can take out of the container. Instead it captures the idea of executing a side-effect as separate from evaluating business logic.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98