2

I am playing with ZIO and built a simple application that get content via HTTP :

for {
  options <- Options.parse(args)
     http = HttpClient(args)
  content <- Download.execute(args.resource).provide(http)
} yield ()

It does the job but the client is backed by Play StandaloneWsClient and I would like to close it and terminate the actor system as described in the documentation: https://github.com/playframework/play-ws#scala-1

So I created a finaliser method but it seems that is has no effect:

// ...
content <- Download.execute(args.resource).ensuring(http.disconnect()).provide(http)

// ...
class HttpClient {
  // ...
  def disconnect():UIO[Unit] = ZIO.effectTotal { 
    client.close()
    system.terminate()
  }

How can I instruct ZIO to call a finaliser method to free up my resources ?

gervais.b
  • 2,294
  • 2
  • 22
  • 46
  • 2
    If you have a [**Resource**](https://javadoc.io/doc/dev.zio/zio_2.12/latest/zio/ZManaged.html) then use the appropriate abstraction for dealing with them. Also, I would recommend you to always take a look at the [_documentation_](https://zio.dev/docs/overview/overview_handling_resources) before opening a question. – Luis Miguel Mejía Suárez Dec 03 '19 at 17:11
  • Thanks Luis. The documentation say _the `ensuring` operation guarantees that if an effect begins executing and then terminates (for whatever reason), then the finalizer will begin executing._ This is what I have done without success. _bracket_ is more intrusive than _ensuring_ and I may want to release the client ina nother place of my "flow". I was not aware of `ZManaged`but it does not solve my problem because I want to disconnect my client when the effect is done, not _automatically released after the resource is used_ because it is used by many effects. – gervais.b Dec 04 '19 at 07:46
  • If you need to use your resources by many effects you need to need to compose all those effects into one and pass that one to the `use` method. That is the only correct way of handling resource finalization. – Luis Miguel Mejía Suárez Dec 04 '19 at 12:02
  • Luis, thanks for your replies. The code behind `content <- Download.execute(args.resource).provide(http)` create a `Seq[ZIO]` and "compose" them to one via `ZIO.collectAllPar`. – gervais.b Dec 05 '19 at 11:18
  • 1
    So? I do not understand the purpose of your last reply? - Let me expand, what you should do is something like this `content <- HttpClient.fromArgs(args).use { client => Download.execute(args.resource, client) }` and `HttpClient.fromArgs` should return a **ZManaged** of your client, which ensures the close operation is called after the use. – Luis Miguel Mejía Suárez Dec 05 '19 at 12:10

0 Answers0