callInspectorWith method

Future<void> callInspectorWith({
  1. required List<BaseBody> events,
  2. void onCompleted(
    1. String?
    )?,
})

Implementation

Future<void> callInspectorWith(
    {required List<BaseBody> events,
    void Function(String?)? onCompleted}) async {
  if (_sending) {
    onCompleted?.call(
        "Batch sending cancelled because another batch sending is in progress. Your events will be sent with next batch.");
    return;
  }

  if (Random().nextDouble() > samplingRate) {
    if (AvoInspector.shouldLog) {
      print("Avo Inspector: last event schema dropped due to sampling rate.");
    }
    return;
  }

  if (AvoInspector.shouldLog) {
    print("Avo Inspector: events $events");

    events.forEach((event) {
      if (event.type == "sessionStarted") {
        print("Avo Inspector: sending session started event.");
      }
    });
  }

  final listOfEventMaps = events.map((e) => e.toJson()).toList();

  final body = json.encode(listOfEventMaps);

  _sending = true;
  await client
      .post(_trackingEndpoint,
          headers: {"Content-Type": "text/plain"}, body: body)
      .then((response) {
    if (response.statusCode == 200) {
      final body = response.body;
      samplingRate = (json.decode(body)["samplingRate"] + .0);
      _sending = false;
      onCompleted?.call(null);
    } else {
      onCompleted?.call("${response.body} ${response.statusCode}");
    }
  }).onError((error, stackTrace) {
    _sending = false;
    onCompleted?.call(error.toString());
  });
}