I'm not familiar with Completer but I would like to know if it is possible to concatenate a series of Future to handle a data request.
I have to send a List of bytes (data, example; [62,73,65,67,75,13,10]) through a socket connection byte-by-byte and cannot send the next byte before I get an answer from the host. The host will answer with the same character sent (echo) so, once I receive the answer from the host I can then send next char. Working with Future.delayed is too complicate, the delays varies depending on network latency too much, so I was thinking to create Futures with Completer. Don't know how to handle this with Completer but will appreciate any help, suggestion, thanks in advance for any kind of support. Below is part of my code ...
List<Completer<bool>> bytes = [];
@override
void send(dynamic data) async {
bytes.clear();
byteCount = 0;
for (var byte in data) {
bytes.add(Completer<bool>());
byteSent = [byte].toString();
try {
_udpSocket.send([byte], ipAddress!, portNumber!);
await bytes[byteCount].future;
byteCount++;
} catch (e) {
rethrow;
}
}
}
@override
Future<bool> connect() async {
...
reader.listen((data) {
byteReceived = data.toString();
if (byteReceived == byteSent) {
bytes[byteCount].complete(true);
}
buffer.addAll(data);
controller.sink.add(buffer.sublist(0, buffer.length - 2));
});
}
S.
You can modify your code like this to be sure data has been sent sequentially:
Completer<bool> _sendCompleter = Completer<bool>();
@override
void send(List<int> data) async {
for (var byte in data) {
byteSent = byte.toString();
try {
_udpSocket.send([byte], ipAddress!, portNumber!);
await _sendCompleter.future;
} catch (e) {
rethrow;
}
}
}
@override
Future<bool> connect() async {
reader.listen((data) {
byteReceived = data.toString();
buffer.addAll(data);
controller.sink.add(buffer.sublist(0, buffer.length - 2));
_sendCompleter.complete(true);
});
}