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("接口訪問(wèn) count:$count");
? //1.0
//? http.getRequest(isDebounce:isDebounce);
? //2.0
? http.getRequestFunction( () async{
? ? await Future.delayed(Duration(seconds: 1));
? ? print("模擬接口訪問(wèn)返回");
? ? return Future.value(true);
? } ,isDebounce:isDebounce);
? //測(cè)試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("模擬接口訪問(wèn)返回 count:$count");
? ? ? Future.delayed(Duration(seconds:effectivenessTime),(){
? ? ? ? if(isDebounce){
? ? ? ? ? print("可進(jìn)行下一次訪問(wèn)");
? ? ? ? ? _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("可進(jìn)行下一次訪問(wèn)");
? ? ? ? ? _methods.remove(identify);
? ? ? ? }
? ? ? });
? });
? }
}
’‘’