Last active
June 4, 2020 17:37
-
-
Save MisterJimson/e715f339c8d8c1018f22fec995ba5fb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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