-
Notifications
You must be signed in to change notification settings - Fork 9
Managing list of download
Kim, Hyoun Woo edited this page May 26, 2016
·
3 revisions
Q: I have a list of urls & want to download files from those urls sequentially. How can I do that with UniRX ?
A: Create List<IObservable>. and select actions,
// does not run yet. var downloadList = new List<IObservable<byte[]>>(); for (int i = 0; i < 10; i++) { if (true) // Resouces.Load == null... { var downloadAction = ObservableWWW.GetAndGetBytes("http://aaa." + i + ".png") .Do(byteArray => // Do(sideeffect only) or Select(return value) { // var tex = }); downloadList.Add(downloadAction); } } // 1. sequential request, does not use result Observable.Concat(downloadList).LastOrDefault().Subscribe(); // 2. sequential request, use result values Observable.Concat(downloadList).ToArray().Subscribe(); // 3. concurrent request Observable.WhenAll(downloadList).Subscribe(); // 4. choose concurrent count Observable.Merge(downloadList, maxConcurrent: 3).Subscribe();
More option, use FromCoroutine and ToYieldInstruction is simple and readable way.
IObservable<Unit> SequentialLoad() { return Observable.FromCoroutine<Unit>(observer => SequentialLoadCore(observer)); } IEnumerator SequentialLoadCore(IObserver<Unit> observer) { for (int i = 0; i < 10; i++) { // ToYieldInstruction can await observbale. var request = ObservableWWW.GetAndGetBytes("url").ToYieldInstruction(); yield return request; // var tex = new Tex2D(request.Result, ....); } observer.OnNext(Unit.Default); // push Unit or all buffer result. observer.OnCompleted(); }