use of com.koushikdutta.async.callback.WritableCallback in project AndroidAsync by koush.
the class Util method pump.
public static void pump(final InputStream is, final long max, final DataSink ds, final CompletedCallback callback) {
final CompletedCallback wrapper = new CompletedCallback() {
boolean reported;
@Override
public void onCompleted(Exception ex) {
if (reported)
return;
reported = true;
callback.onCompleted(ex);
}
};
final WritableCallback cb = new WritableCallback() {
int totalRead = 0;
private void cleanup() {
ds.setClosedCallback(null);
ds.setWriteableCallback(null);
pending.recycle();
StreamUtility.closeQuietly(is);
}
ByteBufferList pending = new ByteBufferList();
Allocator allocator = new Allocator();
@Override
public void onWriteable() {
try {
do {
if (!pending.hasRemaining()) {
ByteBuffer b = allocator.allocate();
long toRead = Math.min(max - totalRead, b.capacity());
int read = is.read(b.array(), 0, (int) toRead);
if (read == -1 || totalRead == max) {
cleanup();
wrapper.onCompleted(null);
return;
}
allocator.track(read);
totalRead += read;
b.position(0);
b.limit(read);
pending.add(b);
}
ds.write(pending);
} while (!pending.hasRemaining());
} catch (Exception e) {
cleanup();
wrapper.onCompleted(e);
}
}
};
ds.setWriteableCallback(cb);
ds.setClosedCallback(wrapper);
cb.onWriteable();
}
Aggregations