JsonRpc2Client constructor

JsonRpc2Client(
  1. String? clientId,
  2. StreamChannel<String> channel
)

Implementation

JsonRpc2Client(String? clientId, StreamChannel<String> channel) {
  _clientId = clientId;
  _peer = json_rpc_2.Peer(channel);

  _peer!.registerMethod('event', (json_rpc_2.Parameters params) {
    String? eventName = params['event_name'].asString;
    var event = params['value'].value;
    for (var s in _subscriptions.where((s) => s.eventName == eventName)) {
      if (!s._stream.isClosed) s._stream.add(event);
    }
  });

  _peer!.registerFallback((json_rpc_2.Parameters params) {
    var c = _requests.remove(params.method);

    if (c == null) {
      throw json_rpc_2.RpcException.methodNotFound(params.method);
    } else {
      var data = params.asMap;

      if (data['status'] is! bool) {
        c.completeError(
            FormatException('The server sent an invalid response.'));
      } else if (!(data['status'] as bool)) {
        c.completeError(PubSubException(data['error_message']?.toString() ??
            'The server sent a failure response, but did not provide an error message.'));
      } else {
        c.complete(data);
      }
    }
  });

  _peer!.listen();
}