cacheAndNetwork method

Stream<Response> cacheAndNetwork(
  1. Request request
)

Retrieve response from the cache if available and then from the network. Returns Stream<ApiResponse> type.

Implementation

Stream<Response> cacheAndNetwork(Request request) async* {
  _throwOnRequestWithoutCacheKey(request);

  /// read cache
  final cacheFuture = cache.read(request.key);

  /// Start network fetch.
  /// Send method automatically updates cache.
  final networkFuture = send(request);

  /// wait for cache response
  final cachedResponse = await cacheFuture;

  /// return cache if available
  if (cachedResponse != null) yield cachedResponse;

  /// wait for network response
  final networkResponse = await networkFuture;

  /// yield network response
  yield networkResponse;
}