Skip to content

Instantly share code, notes, and snippets.

@MisterJimson
Last active June 4, 2020 17:37
Show Gist options
  • Save MisterJimson/e715f339c8d8c1018f22fec995ba5fb5 to your computer and use it in GitHub Desktop.
Save MisterJimson/e715f339c8d8c1018f22fec995ba5fb5 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:mobx/mobx.dart';
class Debounce {
final Duration delay;
Timer _timer;
Debounce(this.delay);
void call(void Function() action) {
_timer?.cancel();
_timer = Timer(delay, action);
}
void dispose() {
_timer?.cancel();
_timer = null;
}
}
ReactionDisposer debounceReaction<T>(
T Function(Reaction) fn, void Function(T) effect,
{String name,
@required Duration debounce,
bool fireImmediately,
EqualityComparer<T> equals,
ReactiveContext context,
void Function(Object, Reaction) onError}) {
var debounceHandler = Debounce(debounce);
var reactionDisposer = reaction<T>(
fn,
(x) {
debounceHandler(() {
print(x);
effect(x);
});
},
name: name,
fireImmediately: fireImmediately,
equals: equals,
context: context,
onError: onError,
);
return DebounceReactionDisposer(
reactionDisposer.reaction,
debounceHandler,
);
}
class DebounceReactionDisposer extends ReactionDisposer {
final Debounce _debounce;
DebounceReactionDisposer(Reaction reaction, this._debounce) : super(reaction);
@override
void call() {
_debounce.dispose();
super.call();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment