asynchronous - 键值未来任务队列
问题描述
我想创建一个未来任务队列,并使用一个键来避免将已添加的相同任务添加到队列中。
这是我的场景:
- 对 url1 的异步调用
- 对 url1 的异步调用
- 对 url2 的异步调用
我需要的是:
- 将对 url1 的调用添加到队列并执行它
- 不要将对 url1 的第二次调用添加到队列中并丢弃它
- 将对url2的调用加入队列,等待对url1的调用完成,然后执行
我阅读了有关 StreamQueue 和 Queue 的信息,但我不知道它是否适合我的需要。
我读到的另一个结构是await for
流。
所以我尝试了类似的东西:
await for (var url in stream) { // <--- I do not know how create this stream
var url = Uri.https('www.example.com', url);
List<dynamic> tmpItems;
try {
http.Response res = await http.get(url);
final data = json.decode(res.body);
tmpItems = _parseItems(data["data"]);
} catch(e) {
print(e);
}
if (this.mounted) {
return setState(() {
_items.addAll(tmpItems ?? []);
});
}
}
我不知道如何创建stream
和添加对它的调用。
解决方案
好的,首先你需要有一个 urlArray 有 url 然后实现一个名为 getUrl 的异步方法作为示例并实现它以从 url 获取数据此方法将 url 作为参数
Future getData(url,index) async {
//here you can call the function and handle the output(return value) as result
getUrl(url).then((result) {
// print(result);
//here check if index is smaller than the array length-1
//if true then call getData function again to get next url
if(index<urlArray.length)
{
--index;
getData(urlArray[index],index);
}
});
}
所以第一次调用会是这样的 getData(urlArray[0],0)
推荐阅读
- c# - Unity 3D How to check if a gameobject remained in the same position every x amount of time?
- google-apps-script - Google 表格自定义函数支持多少 JsDoc?
- regex - Perl中输入文件的正则表达式
- r - 如何使用 if 和 else 条件创建新列
- typescript - 如何使用它的声明来定义一个函数?
- mysql - MySQL:char(4) 之间的性能差异比 smallint(5, unisgned) 更快
- wordpress - 基于浏览器的不同响应
- apache-spark - 如何使用 spark-submit 在 Kubernetes (minikube) 上提交 PySpark 作业
- reactjs - 有没有办法将自定义变体添加到排版?
- amazon-web-services - AWS Lambda 错误:在类上找不到名为“minFunction”且具有适当方法签名的公共方法