Created
September 21, 2022 01:03
-
-
Save VB10/0a68432a28103f893690be20c7d5edc2 to your computer and use it in GitHub Desktop.
Manage your future
This file contains hidden or 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 'package:async/async.dart'; | |
class CancelableCustomOperation<T> { | |
CancelableOperation<T?>? _cancellableOperation; | |
final _delayTime = const Duration(milliseconds: 300); | |
final void Function(T value) onChanged; | |
T? data; | |
CancelableCustomOperation( | |
this.onChanged, { | |
this.data, | |
}) { | |
_init(); | |
} | |
void _init() { | |
_cancellableOperation = CancelableOperation.fromFuture( | |
Future.delayed(_delayTime, () { | |
if (data == null) return null; | |
return data; | |
}), | |
onCancel: () { | |
_cancellableOperation = null; | |
}, | |
); | |
} | |
Future<void> onItemChanged(T value) async { | |
await _cancellableOperation?.cancel(); | |
data = value; | |
_init(); | |
final response = await _cancellableOperation?.value; | |
if (response == null) return; | |
onChanged(response); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment