Created
October 6, 2020 10:17
-
-
Save mattbenic/5a7fc82b75412bf141e7eb16c610e1ed to your computer and use it in GitHub Desktop.
Batch downloader that runs multiple download coroutines in parallel using a provided host MonoBehaviour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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