Home > Software engineering >  How to reserve ZIO response inside a custom method in
How to reserve ZIO response inside a custom method in

Time:12-09

I have this method


import ClientServer.*
import zio.http.{Client, *}
import zio.json.*
import zio.http.model.Method
import zio.{ExitCode, URIO, ZIO}
import sttp.capabilities.*
import sttp.client3.Request
import zio.*
import zio.http.model.Headers.Header
import zio.http.model.Version.Http_1_0
import zio.stream.*
import java.net.InetAddress
import sttp.model.sse.ServerSentEvent
import sttp.client3._



object fillFileWithLeagues:

  def fill = for {
    openDotaResponse <- Client.request("https://api.opendota.com/api/leagues")
    bodyOfResponse <- openDotaResponse.body.asString
    listOfLeagues <- ZIO.fromEither(bodyOfResponse.fromJson[List[League]].left.map(error => new Exception(error)))
    save = FileStorage.saveToFile(listOfLeagues.toJson) //Ok
    }yield ()
    println("Im here fillFileWithLeagues.fill ")

and when I try use

fillFileWithLeagues.fill

nothing happens

I'm trying fill file with data from target api using

fillFileWithLeagues.fill
def readFromFileV8(path: Path = Path("src", "main", "resources", "data.json")): ZIO[Any, Throwable, String] =
  val zioStr = (for bool <- Files.isReadable(path) yield bool).flatMap(bool =>
  if (bool) Files.readAllLines(path, Charset.Standard.utf8).map(_.head)
  else {
    fillFileWithLeagues.fill
    wait(10000)
    println("im here readFromFileV8")
    readFromFileV8()})
  zioStr

I'm expecting data.json file must created from

Client.request("https://api.opendota.com/api/leagues")

but there is nothing happens

Maybe I should use some sttp, or some other tools?

CodePudding user response:

If we fix indentation of the code we'll find this:

object fillFileWithLeagues {

  def fill = {
    for {
      openDotaResponse <- Client.request("https://api.opendota.com/api/leagues")
      bodyOfResponse <- openDotaResponse.body.asString
      listOfLeagues <- ZIO.fromEither(bodyOfResponse.fromJson[List[League]].left.map(error => new Exception(error)))
      save = FileStorage.saveToFile(listOfLeagues.toJson) //Ok
    } yield ()
  }

  println("Im here fillFileWithLeagues.fill ")
}

As you see the println is part of fillFileWithLeagues, not of fill.

Another potential problem is that an expression like fillFileWithLeagues.fill only returns a ZIO instance, it is not yet evaluated. To evaluate it, it needs to be run. For example as follows:

import zio._

object MainApp extends ZIOAppDefault {
  def run = fillFileWithLeagues.fill
}
  • Related