0

I have a question about IO monad. I opened some InputStream and want to use IO to read from it. Here is the example:

def read(io: IO[Option[Array[Byte]]]): IO[Unit] = IO {
  io.unsafeRunSync() match {
    case Some(b) => 
         //do some with b
         read(io)
    case None => 
         ()
  }
}

The thing I'm confused about is that I read from the same IO instance multiple times modifying its state. It does not look like referential transparent method. Is it common to do this way or there is something more FP style?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 2
    You don't want to invoke `unsafeRunSync()` in your library code. You only invoke it _once_ on the very outer layer, e.g. in the `main` method. – Tomas Mikula May 29 '18 at 15:59
  • 2
    `IO { io.unsafeRunSync() ... }` seems suspicious. Are you still defining the pure immutable plan represented by `IO`, or are you running it already? – Andrey Tyukin May 29 '18 at 16:03

0 Answers0