executeStream method

Stream<RxResult<T>> executeStream()

Stream方式(支持轮询)

Implementation

Stream<RxResult<T>> executeStream() async* {
  if (TextUtil.isEmpty(_path)) {
    yield RxResult.error(
        Exception("The request path cannot be empty path:$_path"));
    return;
  }

  if (!(await _checkNetWork())) {
    yield RxResult.error(NetworkException("Network not available"));
    return;
  }

  _cacheMode ??= (_rxNet.getBaseCacheMode() ?? CacheMode.ONLY_REQUEST);

  bool keepLooping;
  do {
    keepLooping = _isLoop;
    switch (_cacheMode!) {
      case CacheMode.ONLY_REQUEST:
        yield* _networkRequestStream(shouldCache: false);
        break;
      case CacheMode.FIRST_USE_CACHE_THEN_REQUEST:
        try {
          final cacheResult = await _readCache();
          yield cacheResult;
        } catch (e) {
          // Cache errors are ignored, proceed to network.
        }
        yield* _networkRequestStream(shouldCache: true);
        break;
      case CacheMode.REQUEST_FAILED_READ_CACHE:
        RxResult<T>? networkResult;
        await for (final netResult
            in _networkRequestStream(shouldCache: true)) {
          networkResult = netResult;
        }

        if (networkResult != null && networkResult.isSuccess) {
          yield networkResult;
        } else {
          try {
            final cacheResult = await _readCache();
            yield cacheResult;
          } catch (e) {
            // 缓存也失败时,才把网络错误抛给调用方,避免同一次请求
            // 同时触发 failure 和 success 回调。
            if (networkResult != null) {
              yield networkResult;
            }
          }
        }
        break;
      case CacheMode.CACHE_EMPTY_OR_EXPIRED_THEN_REQUEST:
        bool yieldedFromCache = false;
        if (!_requestIgnoreCacheTime) {
          try {
            final cacheResult = await _readCache();
            yield cacheResult;
            yieldedFromCache = true;
          } catch (e) {
            // Cache failed, proceed to network.
          }
        }
        //缓存超时间-失效,执行新请求
        if (!yieldedFromCache) {
          yield* _networkRequestStream(shouldCache: true);
        }
        break;
      case CacheMode.ONLY_CACHE:
        try {
          final cacheResult = await _readCache();
          yield cacheResult;
        } catch (e) {
          yield RxResult.error(e);
        }
        break;
    }

    if (keepLooping) {
      await Future.delayed(_loopInterval);
    }
  } while (keepLooping);
}