Search code examples
c#reactive-programmingsystem.reactivereactiveunirx

Is there a way to specify a variable number of Observable in Observable.WhenAll()?


I'm applying reactive programming to the Unity3D project. Is there a way to specify a variable number of Observable in Observable.WhenAll()?

Sample or search results suggest an explicit way to enter all non-variable items, most of which are not variable numbers.

var parallel = Observable.WhenAll(
                    ObservableWWW.Get ("http://google.com/"),
                    ObservableWWW.Get ("http://bing.com/"),
                    ObservableWWW.Get ("http://unity3d.com/");

What I want is as follows.

List<string> URLs = new List<string>();
URLs.Add("http://google.com/");
URLs.Add("http://bing.com/");
...
...
var parallel = Observable.WhenAll( ??? //ObservableWWW.Get() : count of URLs list);

Please reply. Thank you.


Solution

  • WhenAll(this IEnumerable> sources) already does this. I suspect the real question is how to produce some observables from a list of URLs. One way to do it would be to use LINQ :

    var urlObservables=URLs.Select(url=>ObservableWWW.Get(url));
    
    var allAsOne= Observable.WhenAll(urlObservables);
    

    Update

    As Felix Keil commented, what if the OP wants to observe only a few of those observables? That's a job for LINQ's Take(), applied either on the URL list or the observables list, eg :

    var someObservables=URLs.Take(2).Select(url=>ObservableWWW.Get(url));
    

    or even

    var someObservables=URLs.Select(url=>ObservableWWW.Get(url)).Take(2);
    

    LINQ's lazy evaluation means the operators will run only when someObservables gets enumerated. When that happens, enumeration will stop after the first two iterations so ObservableWWW.Get will be called only twice