Flutter: debounce 避免高频率事件

函数

import 'dart:async';

Function debounce(Function fn, [int t = 30]) {
  Timer _debounce;
  return () {
    // 还在时间之内,抛弃上一次
    if (_debounce?.isActive ?? false) _debounce.cancel();

    _debounce = Timer(Duration(milliseconds: t), () {
      fn();
    });
  };
}

RaisedButton(
      onPressed: debounce(() {
          print(1);
     }, 3000),
    child: Text('Test'),
)

rxdart

import 'package:rxdart/rxdart.dart';

  final _counterSubject = BehaviorSubject<int>();

  @override
  void initState() {
    super.initState();
    _counterSubject.debounceTime(Duration(seconds: 2)).listen((int i) {
      print(i);
    });
  }

RaisedButton(
  onPressed: () {
    _counterSubject.add(1);
  },
  child: Text('Test'),
)
posted @ 2019-07-07 22:58  Ajanuw  阅读(1806)  评论(0编辑  收藏  举报