Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

In the process of front and back end interconnection, the problem of repeated requests caused by quick and repeated clicks is often encountered. If not handled properly, garbage data is easily generated on the one hand, and many unnecessary requests are increased on the other hand, resulting in excessive number of server requests. In GetX, a Worker class is provided for this scenario, along with several check subroutines to solve this problem.

Scenario 1: Click like crazy

For example, some shopping App will provide interactive games, by clicking the number of times in the limited time to brush a red envelope or coupons (are routines 😎), at this time we will click frantically from heaven a red envelope or brocade carp, imagine if every click on the request to the backend, that if is tens of thousands of people are so click, the server will be collapse! In this case, GetX provides a debounce function that performs the specified callback only once within a specified period of time:

Worker debounce<T>(
  RxInterface<T> listener,
  WorkerCallback<T> callback, {
  Duration? time,
  Function? onError,
  void Function()? onDone,
  bool? cancelOnError,
});
Copy the code

Where listener is the state variable, callback is the callback method when the state variable listener changes, and time is the specified time. The result of these three arguments is that the callback will not be executed if the listener continues to change for a period less than time. Callback is called once if no change has occurred for more than the time duration. For example, let’s set a counter counter as follows:

debounce(_counter, (latestValue) => print("callback: $latestValue"), time: Duration(seconds: 1));
Copy the code

Then there’s a button that increments the value of the counter every time it’s clicked. If our hands are fast enough, we can click many times a second. At this point, if we want to prevent shaking, we can put network requests into callback, so as to avoid excessive network requests caused by crazy clicks for a limited time, resulting in a dDOS-like attack effect. Let’s take a look at the effect, as shown below.

As you can see, when we frantically click, the callback is not executed, but is executed after a certain interval (1 second). This way you can reduce unnecessary requests. This scenario can also be used in search situations, where instead of asking for back-end data while typing, because the content is changing, we wait until the user finishes typing, which gives a better experience and reduces back-end requests.

Scene 2: Gold coins

In some cases, we need to limit the number of requests within a certain period of time, which is similar to the effect of limiting traffic. For example, if you click the button to swipe gold, we can limit it to one swipe every 2 seconds, so that it can only swipe gold 30 times in a minute. GetX provides an interval method:

Worker interval<T>(
  RxInterface<T> listener,
  WorkerCallback<T> callback, {
  Duration time = const Duration(seconds: 1),
  dynamic condition = true.Function? onError,
  void Function()? onDone,
  bool? cancelOnError,
})
Copy the code

The use is similar to debounce, except that changes in the interval time range are ignored and callback is called once every time the state variable changes. Also added a condition (a function that returns true or false), and callback will only be executed if the function returns true (i.e., it must be VIP to swipe gold). Let’s take a counter as an example.

class WorkerController extends GetxController {
  final _counter = 0.obs;
  set counter(value) => this._counter.value = value;
  get counter => this._counter.value;

  late Worker worker;
  int coinCount = 0;

  @override
  void onInit() {
    worker = interval(
      _counter,
      (_) {
        coinCount++;
        print("Gold coins:$coinCount");
      },
      time: Duration(seconds: 2),
      condition: () => coinCount < 10,);super.onInit();
  }

  @override
  void dispose() {
    worker.dispose();
    super.dispose(); }}Copy the code

You can see that the gold count increases by 1 every second, and then stops increasing after 10.

Other Worker hook subfunctions

GetX also provides the following three Worker hook subfunctions, which are called the same as interval.

  • once: Execute only once when the status variable changes. For example, update the details page only once.
  • ever: Executes every change, and can be used for likes
  • everAll: used for list-type state variables that perform callbacks whenever list elements change.

Worker Usage precautions

To prevent workers from being repeatedly registered, they should be registered in the constructor of GetxController or onInit declaration cycles, or in initState of StatefulWidget (not recommended). Note that the Worker’s dispose method needs to be called in the Dispose method to destroy the Worker object.

conclusion

This paper introduces the use of GetX Worker class and the corresponding tick sub function. By registering Worker, it can be used for application shaking prevention and flow limiting, so as to prevent false trigger and reduce the number of server requests and reduce resource consumption.

I am dao Code Farmer with the same name as my wechat official account. This is a column about the introduction and practice of Flutter, providing systematic learning articles about Flutter. See the corresponding source code here: The source code of Flutter Introduction and Practical column. If you have any questions, please add me to the wechat account: island-coder.

👍🏻 : feel the harvest please point a praise to encourage!

🌟 : Collect articles, easy to look back!

💬 : Comment exchange, mutual progress!