scalaz / scalaz-nio

Performant, purely-functional, low-level, and unopinionated wrapper around Java NIO functionality
Apache License 2.0
84 stars 29 forks source link

Use ZIO's Managed to handle cleaning resources #42

Open ghostdogpr opened 6 years ago

ghostdogpr commented 6 years ago

How about using Managed from ZIO to avoid having users (forgetting) invoke close explicitly?

For example:

def apply(): Managed[Exception, AsynchronousServerSocketChannel] =
    IO.syncException(JAsynchronousServerSocketChannel.open())
      .map(new AsynchronousServerSocketChannel(_)).managed(_.close.catchAll(_ => IO.unit))

Then when using it:

AsynchronousServerSocketChannel().use { server =>
 // logic here
}

Or if we want to keep the wrapper API low-level, there could be another higher-level API that does something like that:

SockerServer.start(1337).use { server =>
 // logic here
}

where the acquire operation would create the channel and call bind, and the release operation would close it.

How do you think?

ysusuk commented 6 years ago

it sounds very reasonable to me! I'm wondering how well it will be aligned with our general IO effect?

ghostdogpr commented 6 years ago

The use function takes an IO and returns an IO, so I guess we're still aligned?

I got the idea watching this talk: https://speakerdeck.com/iravid/boring-usecases-for-exciting-types?slide=53 (ZIO and Managed are mentioned at the end).

ysusuk commented 6 years ago

Hi @ghostdogpr, thank you for the link! I think it makes total sense, but i would probably rather have it as alternative (have both apply => IO and apply => Managed), since we are trying to be as unopinionated as possible on how to use this API! User can always do bracket or ensuring. Would you like to do a pull request with a usage example? =)

ghostdogpr commented 6 years ago

Yeah, it makes sense to allow both. This one could just be a helper method in the companion object. I’ll work on a PR.

ysusuk commented 6 years ago

@ghostdogpr, thanks a lot!

ysusuk commented 6 years ago

@ghostdogpr you can as well join our gitter channel