I am trying to play around with ZIO http using their simples hello world example. I have a Java-written service which does some logic, and it expecting a handler function, so it can call it when result is ready. How do I user it together with ZIO http ? I want something like this:
object HelloWorld extends App {
def app(service: JavaService) = Http.collect[Request] {
case Method.GET -> Root / "text" => {
service.doSomeStuffWIthCallback((s:String) => Response.text(s))
}
}
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app(new JavaService)).exitCode
}
Basically I want to send ZIO HTTP response from the callback function, I am just not sure how to go about that. Thanks.
CodePudding user response:
You should wrap your Java service with callback with effectAsync
, something like this:
def doSomeStuffWrapped(service: JavaService): Task[String] = {
IO.effectAsync[Any, Throwable, String] { cb =>
service.doSomeStuffWIthCallback((s: String) => {
// Success case
cb(IO.succeed(s))
// Optional error case?
// cb(IO.fail(someException))
})
}
}
Then use regular ZIO constructs to build the HTTP response.
You might want to see this article presenting different options for wrapping impure code in ZIO: https://medium.com/@ghostdogpr/wrapping-impure-code-with-zio-9265c219e2e