Skip to content

Instantly share code, notes, and snippets.

@X601169957911
Forked from mattbenic/BatchDownloader.cs
Created March 24, 2022 11:42
Show Gist options
  • Save X601169957911/dddd7bc708463be6a0306f227181078d to your computer and use it in GitHub Desktop.
Save X601169957911/dddd7bc708463be6a0306f227181078d to your computer and use it in GitHub Desktop.
Batch downloader that runs multiple download coroutines in parallel using a provided host MonoBehaviour
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace MB.Other
{
public class BatchDownloader
{
private readonly IEnumerable<Func<IEnumerator>> downloadFuncs;
private readonly Action<int, int> onDownloadComplete;
private readonly Action<int> onAllDownloadsComplete;
private readonly int totalDownloadsCount;
private int completedDownloadsCount;
public BatchDownloader(
IEnumerable<Func<IEnumerator>> downloadFuncs,
Action<int, int> onDownloadComplete = null,
Action<int> onAllDownloadsComplete = null)
{
this.downloadFuncs = downloadFuncs;
this.onDownloadComplete = onDownloadComplete;
this.onAllDownloadsComplete = onAllDownloadsComplete;
totalDownloadsCount = downloadFuncs.Count();
}
public IEnumerator DownloadBatch(MonoBehaviour coroutineRunner)
{
completedDownloadsCount = 0;
foreach (var downloadFuncs in downloadFuncs)
coroutineRunner.StartCoroutine(ProcessDownload(downloadFuncs));
while (totalDownloadsCount != completedDownloadsCount)
yield return null;
onAllDownloadsComplete?.Invoke(totalDownloadsCount);
}
private IEnumerator ProcessDownload(Func<IEnumerator> downloadFunc)
{
yield return downloadFunc();
completedDownloadsCount++;
onDownloadComplete?.Invoke(totalDownloadsCount, completedDownloadsCount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment