call method

Future<Object?> call(
  1. String service,
  2. String method, {
  3. Map<String, dynamic> params = const {},
  4. Object? fallback()?,
})

Calls method of service on the main app and returns its result.

When the main app is disconnected, returns fallback's value if given, and throws FloatyProxyDisconnectedException otherwise.

Implementation

Future<Object?> call(
  String service,
  String method, {
  Map<String, dynamic> params = const {},
  Object? Function()? fallback,
}) async {
  if (!FloatyConnectionState.isMainAppConnected) {
    if (fallback != null) return fallback();
    throw FloatyProxyDisconnectedException(service, method);
  }
  final id = '${_nextId++}';
  final completer = Completer<Object?>();
  _pending[id] = completer;
  _timers[id] = Timer(timeout, () {
    _pending.remove(id);
    _timers.remove(id);
    if (completer.isCompleted) return;
    completer.completeError(FloatyProxyTimeoutException(service, method));
  });
  final sent = FloatyChannel.sendSystem(_prefix, {
    'id': id,
    'type': 'request',
    'service': service,
    'method': method,
    'params': params,
  });
  final results = await Future.wait<Object?>([
    completer.future,
    sent,
  ], eagerError: true);
  return results.first;
}