简体   繁体   中英

Do proxy in Dart by using noSuchMethod?

I have many service classes which simply do the http requests, and I want to count the number of currently running http requests. My naive idea is to use a proxy like -

int currentRunHttpRequestCounter = 0;

class MyProxy {
  noSuchMethod() {
    currentRunHttpRequestCounter+=1;
    magically_call_the_original_class(...);
    currentRunHttpRequestCounter-=1;
  }
}

However, I do not know how to magically_call_the_original_class ? In other words, how do I create a proxy that passes every method call down to the original class?

Thanks!

create one abstract HTTP service with static counter. inside that abstract service use counter and logging inside your HTTP methods.

Then extend that service into mocked or real service, and every time you call it it will update the counter.


class Counter {
  var getCount = 0;
}

abstract class HttpService {
  static Counter counter = Counter();
  
  Future<dynamic> get(Map<String, dynamic> query) {
    counter.getCount++;
    // use for logging ect
  }
}

class HttpMockedService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

class HttpRealService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

This is simplified solution, but you can play with many approaches to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM