loadAppOpenAd method

void loadAppOpenAd({
  1. int maxLoadAttempts = 5,
  2. int attemptDelayFactorMs = 500,
  3. String? adId,
})

<------------------------ Load AppOpenAd with Exponential Backoff ------------------------>

Implementation

void loadAppOpenAd({
  int maxLoadAttempts = 5,
  int attemptDelayFactorMs = 500,
  String? adId,
}) {
  final instance = AdmobEasy.instance;
  final appOpenAdID = adId ?? instance.appOpenAdID;
  if (appOpenAdID.isEmpty || _isShowingAd) return;

  // Dispose existing ad if present
  if (_appOpenAd != null) {
    _appOpenAd!.dispose();
    _appOpenAd = null;
  }

  AppOpenAd.load(
    adUnitId: appOpenAdID,
    request: const AdRequest(),
    adLoadCallback: AppOpenAdLoadCallback(
      onAdLoaded: (ad) {
        _appOpenAd = ad;
        _numAppOpenAdLoadAttempts = 0; // Reset attempt counter
        AdmobEasyLogger.success('App open ad loaded');
      },
      onAdFailedToLoad: (error) async {
        AdmobEasyLogger.error('AppOpenAd failed to load: $error');
        _appOpenAd = null;
        _numAppOpenAdLoadAttempts += 1;

        // Retry with exponential backoff if attempts are less than maxLoadAttempts
        if (_numAppOpenAdLoadAttempts < maxLoadAttempts) {
          int delayMs = attemptDelayFactorMs * _numAppOpenAdLoadAttempts;
          await Future.delayed(Duration(milliseconds: delayMs));
          loadAppOpenAd(
            maxLoadAttempts: maxLoadAttempts,
            attemptDelayFactorMs: attemptDelayFactorMs,
            adId: adId,
          ); // Retry loading the app open ad
        } else {
          _numAppOpenAdLoadAttempts = 0; // Reset after reaching max attempts
        }
      },
    ),
  );
}