initDownload static method

Future<StreamSubscription> initDownload(
  1. String url,
  2. DownloaderUtils options
)

Init a new Download, however this returns a StreamSubscription use at your own risk.

Implementation

static Future<StreamSubscription> initDownload(
    String url, DownloaderUtils options) async {
  var lastProgress = await options.progress.getProgress(url);
  final client = options.client ?? Dio(BaseOptions(sendTimeout: 60));
  // ignore: cancel_subscriptions
  StreamSubscription? subscription;
  try {
    isDownloading = true;
    final file = await options.file.create(recursive: true);
    final response = await client.get(
      url,
      options: Options(
          responseType: ResponseType.stream,
          headers: {HttpHeaders.rangeHeader: 'bytes=$lastProgress-'}),
    );
    final sink = await file.open(mode: FileMode.writeOnlyAppend);
    subscription = response.data.stream.listen(
      (Uint8List data) async {
        subscription!.pause();
        await sink.writeFrom(data);
        final currentProgress = lastProgress + data.length;
        await options.progress.setProgress(url, currentProgress.toInt());
        currentProgressLength = currentProgress;
        lastProgress = currentProgress;
        subscription.resume();
      },
      onDone: () async {
        options.progressCallback.call(currentProgressLength, url);
        options.onDone.call();
        await sink.close();
        if (options.client != null) client.close();
      },
      onError: (error) async {
        options.error.call();
        subscription!.pause();
      },
    );
    return subscription!;
  } catch (e) {
    rethrow;
  }
}