waitMessage function
Wait Message from stream web socket
id
or type
must defined
Implementation
Future<SocketData> waitMessage(Stream stream,
{String? id,
String? type,
Function? onTimeout,
Duration duration = const Duration(seconds: 30)}) async {
try {
// print(' $id $type');
assert(id != null || type != null, "[id] or [type] must defined");
var completer = Completer.sync();
var _subscription = stream.timeout(duration, onTimeout: (sink) {
if (onTimeout != null) {
onTimeout();
}
sink.close();
completer.complete(null);
}).where((event) {
// print("SOCKET EVENT ON WAIT MESSAGE: $event");
try {
var _d = SocketData.fromSocket(event);
if (type != null && id != null) {
return _d.type == type && _d.messageId == id;
} else if (type == null && id != null) {
return _d.messageId == id;
} else if (id == null && type != null) {
return _d.type == type;
} else {
return true;
}
} on Exception {
//TODO:ADD ERROR ON ANALYSIS
completer.complete(null);
return false;
}
}).listen((event) {
// print("SOCKET LISTEN : $event");
completer.complete(event);
});
var completed = await completer.future;
// print(completed);
await _subscription.cancel();
if (completed != null) {
// print('IS NOT EMPTY : $completed');
return SocketData.fromSocket(completed);
} else {
// print('IS EMPTY');
return SocketData.fromFullData({
"reason": "Message Not Found In Expected Time",
"message_type": type,
"success": false,
"data": {}
});
}
} on Exception catch (e) {
return SocketData.fromFullData({
"reason": "Message Not Found : $e",
"message_type": type,
"success": false,
"data": {}
});
}
}