Home > front end >  How to extract value from Scala cats IO
How to extract value from Scala cats IO

Time:04-28

I need to get Array[Byte] value from ioArray which is IO[Array[Byte]] // IO is from cats library

  object MyTransactionInputApp extends App{

     val ioArray : IO[Array[Byte]] = generateKryoBinary()
  

     val i : Array[Byte] = ioArray.unsafeRunSync();

      println(i)

  def generateKryoBinaryIO(transaction: Transaction): IO[Array[Byte]] = {
    KryoSerializer
      .forAsync[IO](kryoRegistrar)
      .use { implicit kryo =>
          transaction.toBinary.liftTo[IO]
      }
  }

  def generateKryoBinary(): IO[Array[Byte]] =  {
    val transaction = new Transaction(Hash(""),"","","","","")
    val ioArray =  generateKryoBinaryIO(transaction);
    return ioArray
  }

}

I tried the below, but not working

 val i : Array[Byte] = for {
    array <- ioArray
  } yield array

CodePudding user response:

If you just started working with cats-effect I recommend reading about cats.effect.IOApp which runs your IO.

Otherwise simple solutions would be:

  1. run it explicitly and get the result:
import cats.effect.unsafe.implicits.global

ioArray.unsafeRunSync()
  1. or maybe work with Future:
import cats.effect.unsafe.implicits.global

ioArray.unsafeToFuture()

Could you give us more context about your application ?

  • Related