I have a list of urls that I have to check sequentially. When one of the content retrieved at the url matches a given criteria I have to stop otherwise the next url has to be tested.
The problem is that retrieving content for a given url is an asynchronous task so I can't use a simple for-each loop.
What is the best way to do that ?
For now my code looks like that :
List<String> urls = [/*...*/];
void f() {
if (urls.isEmpty) return; // no more url available
final url = urls.removeAt(0);
getContent(url).then((content) {
if (!matchCriteria(content)) f(); // try with next url
else doSomethingIfMatch();
});
}
f();
The Quiver package contains several functions to iterate with async.
doWhileAsync,reduceAsyncandforEachAsyncperform async computations on the elements of on Iterables, waiting for the computation to complete before processing the next element.
doWhileAsync seems to be exactly what is wanted :
List<String> urls = [/*...*/];
doWhileAsync(urls, (url) => getContent(url).then((content) {
if (!matchCriteria(content)) {
return new Future.value(true); // try with next url
} else {
doSomethingIfMatch();
return new Future.value(false);
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With