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 _total = int.tryParse(
            response.headers.value(HttpHeaders.contentLengthHeader)!) ??
        0;
    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());
        options.progressCallback.call(currentProgress, _total);
        lastProgress = currentProgress;
        subscription.resume();
      },
      onDone: () async {
        options.onDone.call();
        await sink.close();
        if (options.client != null) client.close();
      },
      onError: (error) async => subscription!.pause(),
    );
    return subscription!;
  } catch (e) {
    rethrow;
  }
}