request<TRequest, TResponse> method

Future<TResponse?> request<TRequest, TResponse>(
  1. TRequest payload
)

Implementation

Future<TResponse?> request<TRequest, TResponse>(TRequest payload) async {
  final sendPort = _sendPort;
  if (sendPort == null) {
    throw StateError('Messenger is not attached to an worker');
  }

  final request = AudioIsolateHostRequest(payload);
  final responseFuture = message.firstWhere((r) => r is AudioIsolateWorkerResponse && r.requestId == request.id);
  sendPort.send(request);

  final AudioIsolateWorkerResponse response;
  try {
    response = await responseFuture as AudioIsolateWorkerResponse;
  } on StateError {
    return null;
  }

  switch (response) {
    case AudioIsolateWorkerSuccessResponse():
      if (response.payload is TResponse) {
        return response.payload as TResponse;
      } else {
        throw StateError('Unexpected response type: ${response.payload.runtimeType}');
      }
    case AudioIsolateWorkerFailedResponse():
      return Future.error(response.exception, response.stackTrace);
  }
}