willFreeIn method

Duration willFreeIn({
  1. String? methodId,
})

Returns minimum required time until request [of class] can be sent

Returns Duration.zero if the request can be sent immediately

Must be checked again before sending the request, because it returns minimum required time, not the actual one

Implementation

Duration willFreeIn({String? methodId}) {
  // Time since last request
  final timePassed = DateTime.now().difference(_lastRequest);

  // Return delay caused by global timer
  // if not enough time has passed yet
  if (methodId == null) {
    if (timePassed < globalTimeout) {
      return globalTimeout - timePassed;
    }
  }

  // If request class is specified
  if (methodId != null) {
    // Time since last request of time has sent
    final methodTimePassed =
        DateTime.now().difference(lastRequest(methodId: methodId));

    // Minimum delay if the request is being sent right now
    // This works so because the running request can finish with
    // an error, so the next request will be able to be sent immediately
    if (isMethodBusy(methodId)) {
      return Duration(milliseconds: 1);
    }

    // Get configured timeout
    final requestTimeout = getMethodRequestTimeout(methodId);
    // If not enough time passed for the class - return difference
    if (requestTimeout > methodTimePassed) {
      return requestTimeout - methodTimePassed;
    }
  }

  // Can be sent immediately
  return Duration.zero;
}