invoke method

Future invoke(
  1. String methodName, {
  2. List? args,
})

Invokes a hub method on the server using the specified name and arguments.

The Future returned by this method resolves when the server indicates it has finished invoking the method. When the future resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of resolving the Future.

Implementation

Future<dynamic> invoke(String methodName, {List<dynamic>? args}) {
  final streamParameters = _replaceStreamParameters(args);
  final invocationDescriptor = _createInvocation(
    methodName: methodName,
    args: args,
    nonblocking: false,
    streamIds: streamParameters.item2,
  );

  final p = Completer<dynamic>();

  _callbacks[invocationDescriptor.invocationId] =
      (HubMessage? invocationEvent, Exception? error) {
    if (error != null) {
      p.completeError(error);
    } else if (invocationEvent != null) {
      // invocationEvent will not be null when an error is not passed to the callback
      if (invocationEvent.type == MessageType.completion) {
        if (invocationEvent is CompletionMessage) {
          if (invocationEvent.error != null) {
            p.completeError(Exception(invocationEvent.error));
          } else {
            p.complete(invocationEvent.result);
          }
        } else {
          p.completeError(
              Exception('Unexpected message type: ${invocationEvent.type}'));
        }
      }
    }
  };

  final futureQueue = _sendWithProtocol(invocationDescriptor).catchError((e) {
    if (e is Object) {
      p.completeError(e);
    }
    _callbacks.remove(invocationDescriptor.invocationId);
  });

  _launchStreams(streamParameters.item1, futureQueue);

  return p.future;
}