invoke<R extends TdObject> method
Sends request and completes with TDLib's typed response.
Throws TdException for a TDLib error, TimeoutException after
timeout (default TdRuntime.defaultTimeout; the TDLib request itself
is not cancelled), or TdClientClosedException if the client closes.
Implementation
Future<R> invoke<R extends TdObject>(
TdFunction<R> request, {
Duration? timeout,
}) {
if (isClosed) return Future.error(TdClientClosedException(id));
if (!runtime._receiving) {
return Future.error(
const TdReceiverException('receive isolate is not running'));
}
final extra = runtime._nextExtra++;
final pending = _Pending(id);
runtime._pending[extra] = pending;
final limit = timeout ?? runtime.defaultTimeout;
pending.timer = Timer(limit, () {
if (runtime._pending.remove(extra) != null) {
pending.fail(TimeoutException(
'TDLib ${request.getConstructor()} timed out', limit));
}
});
try {
tdjson.tdSendJson(id, jsonEncode(request.toJson(extra)));
} catch (error) {
runtime._pending.remove(extra);
pending.timer?.cancel();
return Future.error(error);
}
return pending.completer.future.then<R>((object) {
if (object is TdError) throw TdException(object, request);
if (object is R) return object;
throw TdUnexpectedResponseException(object, request);
});
}