receive method

Future<Map<String, dynamic>> receive(
  1. int id
)

Wait for a response that has the given id, which matches with the sent message.

Implementation

Future<Map<String, dynamic>> receive(int id) {
  var completer = Completer<Map<String, dynamic>>();

  // Create a one-shot subscription to the stream to receive the response.
  late StreamSubscription<dynamic> sub;

  sub = stream.listen((msg) {
    Map<String, dynamic> json =
        jsonDecode(msg as String) as Map<String, dynamic>;

    if (json["id"] == id) {
      // Cancel the subscription as we only want to receive this one specific message.
      sub.cancel();

      if (json.containsKey("error")) {
        completer.completeError(ResException(json));
      } else {
        completer.complete(json);
      }
    }
  });

  return completer.future;
}