-
-
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
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