watchData method

Stream<FetchFirstResponse> watchData({
  1. required String urlPath,
  2. Map<String, String>? headers,
  3. Duration? timeOut,
  4. OfflineFirstFetchPolicy fetchPolicy = OfflineFirstFetchPolicy.cacheThenNetwork,
  5. bool debugMode = false,
})

Implementation

Stream<FetchFirstResponse> watchData({
  required String urlPath,
  Map<String, String>? headers,
  Duration? timeOut,
  OfflineFirstFetchPolicy fetchPolicy = OfflineFirstFetchPolicy.cacheThenNetwork,
  bool debugMode = false,
}) async* {
  final stream = _storage.watch(urlPath);

  if ((fetchPolicy == OfflineFirstFetchPolicy.cacheThenNetwork ||
          fetchPolicy == OfflineFirstFetchPolicy.networkOnly) &&
      !_fetchingUrls.contains(urlPath)) {
    _fetchingUrls.add(urlPath);

    if (debugMode) log("Triggering network fetch in watchData() for $urlPath");

    _fetchFromNetwork(urlPath, headers, timeOut, debugMode).whenComplete(() {
      _fetchingUrls.remove(urlPath);
    });
  }

  await for (final data in stream) {
    if (debugMode) log("Stream update from cache: $data");

    yield FetchFirstResponse(
      data: data,
      status: data != null,
      message: data != null ? "Updated from cache" : "No cached data",
    );
  }
}