For example, i want to read 100500 bytes to an array:
byte[] array = new byte[100500];
int offset = 0;
ByteBuffer buf = ByteBuffer.directBuffer(4096);
channel.read(buffer, null, new LambdaAdapter((count, exception, attachment) -> {
buf.get(array, offset, count);
offset += count; //will not work, offset must be final
if (offset < 100500) {
channel.read(buffer, null, /*what here? must be lambda we are currently in but we can't use it!*/)
}
//here we have our 100500 bytes inside array
});
LambdaAdapter here is simple wrapper that converts CompletionHandler to functional interface with three arguments.
Anyway. Offset can be put to 'attachment' parameter, lambda can be declared beforehand and reused as as field. However, resulting code is always ugly Ugly UGLY.
I was not able to write acceptable solution even for such simple task - what it will look like for complex protocol where reads are interleaved with writes and wrapped in complex logic?
Does anyone know suitable way to deal with async API? If you think that Scala can save the world here, feel free to use it.