Introduction to ZIO NIO
ZIO-NIO is a ZIO wrapper on Java NIO, an opinionated interface with deep ZIO integration that provides type and resource safety.
Installation​
ZIO-NIO
is available via maven repo. Add this to your dependencies in sbt
:
libraryDependencies += "dev.zio" %% "zio-nio" % "2.0.0"
Main Abstractions​
- Using Blocking APIs — How to deal with NIO APIs that block the calling thread
- File Channel — For processing files that are available locally. For every operation a new fiber is started to perform the operation.
- Socket Channel — Provides an API for remote communication with
InetSocket
s. - Resource Management - Avoiding resource leaks
- Character Sets - For encoding or decoding character data.
End-Of-Stream Handling​
When reading from channels, the end of the stream may be reached at any time. This is indicated by the read effect failing with an java.io.EOFException
. If you would prefer to explicitly represent the end-of-stream condition in the error channel, use the eofCheck
extension method:
import zio._
import zio.blocking.Blocking
import zio.nio._
import zio.nio.channels._
import zio.nio.file.Path
import java.io.IOException
val read100: ZIO[Blocking, Option[IOException], Chunk[Byte]] =
FileChannel.open(Path("foo.txt"))
.useNioBlockingOps(_.readChunk(100))
.eofCheck
End-of-stream will be signalled with None
. Any errors will be wrapped in Some
.