copy to dartpad test;
‘’‘dart
typedef HttpRequestMethod = Future<bool> Function();
void main() {
var http = Http();
start(http,isDebounce:true);
}
var count = 0;
void start(Http http,{isDebounce = false}) async{
if(count >= 10){
count = 0;
return;
}
print("接口访问 count:$count");
//1.0
// http.getRequest(isDebounce:isDebounce);
//2.0
http.getRequestFunction( () async{
await Future.delayed(Duration(seconds: 1));
print("模拟接口访问返回");
return Future.value(true);
} ,isDebounce:isDebounce);
//测试sleep
await Future.delayed(Duration(seconds: 1));
count ++;
return start(http,isDebounce:isDebounce);
}
class Http {
List<String> _methods = [];
//isDebounce version 1.0
void getRequest({identify = "getRequest",isDebounce = false,effectivenessTime = 5}){
if(isDebounce){
if(_methods.contains(identify)){
print("被拦截");
return;
}
_methods.add(identify);
}
Future.delayed(Duration(seconds:1),(){
print("模拟接口访问返回 count:$count");
Future.delayed(Duration(seconds:effectivenessTime),(){
if(isDebounce){
print("可进行下一次访问");
_methods.remove(identify);
}
});
});
}
//isDebounce version 2.0
void getRequestFunction(HttpRequestMethod function,{identify = "getRequestFunction",isDebounce = false,effectivenessTime = 5}) {
if(isDebounce){
if(_methods.contains(identify)){
print("被拦截");
return;
}
_methods.add(identify);
}
function().then((isFinish){
Future.delayed(Duration(seconds:effectivenessTime),(){
if(isFinish && isDebounce){
print("可进行下一次访问");
_methods.remove(identify);
}
});
});
}
}
’‘’
网友评论