fetchAction<T> static method

Future<T> fetchAction<T>(
  1. String key,
  2. ApiRequestAction<T> action, {
  3. Map<String, dynamic> requestData = const {},
  4. bool enableCache = true,
  5. bool enableBackgroundFetch = true,
})

Implementation

static Future<T> fetchAction<T>(
  String key,
  ApiRequestAction<T> action, {
  Map<String, dynamic> requestData = const {},
  bool enableCache = true,
  bool enableBackgroundFetch = true,
}) async {
  if (enableCache && _cache.containsKey(key)) {
    final cachedData = retrieveData<T>(key);
    if (cachedData != null) {
      if (enableBackgroundFetch && !isFetching(key)) {
        _fetchActionInBackground(key, action, enableCache, requestData);
      }
      return cachedData;
    }
  }

  Completer<T> completer = Completer<T>();
  await action
      .listen(
        onStart: () {},
        onDone: () {},
        onSuccess: (response) {
          if (enableCache) {
            store(key, response);
          }
          completer.complete(response);
        },
        onError: (e) => completer.completeError(e),
      )
      .whereMap(requestData)
      .execute();

  final data = await completer.future;
  if (enableBackgroundFetch && !isFetching(key)) {
    _fetchActionInBackground(key, action, enableCache, requestData);
  }
  return data;
}