Skip to content

Instantly share code, notes, and snippets.

@OlegIlyenko
Created April 14, 2012 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OlegIlyenko/2387873 to your computer and use it in GitHub Desktop.
Save OlegIlyenko/2387873 to your computer and use it in GitHub Desktop.
import java.io.{FilterInputStream, InputStream}
class ProgressInputStream(in: InputStream, listener: Long => Unit) extends FilterInputStream(in) {
val NotificationThreshold = 8 * 1024;
var unnotifiedByteCount = 0
override def read() = {
val data = super.read()
if (data != -1) notify(1)
data
}
override def read(b: Array[Byte], off: Int, len: Int) = {
val bytesRead = super.read(b, off, len)
if (bytesRead != -1) notify(bytesRead)
bytesRead
}
override def close() {
if (unnotifiedByteCount > 0) {
listener(unnotifiedByteCount)
unnotifiedByteCount = 0
}
super.close()
}
def notify(bytesRead: Int) {
unnotifiedByteCount += bytesRead
if (unnotifiedByteCount >= NotificationThreshold) {
listener(unnotifiedByteCount)
unnotifiedByteCount = 0
}
}
}
object ProgressInputStream {
def apply(in: InputStream, availableBytes: Long, tracker: Progress => Unit) =
new ProgressInputStream(in, new ProgressListener(availableBytes, tracker))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment