Given a collection of Tasks
:
var americanAirlines = new FlightPriceChecker("AA");
...
var runningTasks = new List<Task<IList<FlightPrice>>>
{
americanAirlines.GetPricesAsync(from, to),
delta.GetPricesAsync(from, to),
united.GetPricesAsync(from, to)
};
I would like to process the results of GetPricesAsync()
in whatever order they arrive. Currently, I'm using a while loop to achieve this:
while (runningTasks.Any())
{
// Wait for any task to finish
var completed = await Task.WhenAny(runningTasks);
// Remove from running list
runningTasks.Remove(completed);
// Process the completed task (updates a property we may be binding to)
UpdateCheapestFlight(completed.Result);
}
Is this a problem that can be solved more elegantly using Rx?
I tried to use something like the code below but got stuck because somewhere I'd have to await
each getFlightPriceTask
which would block and only then execute the next one instead of taking the first that's done and then wait for the next:
runningTasks
.ToObservable()
.Select(getFlightPriceTask => .???.)