Skip to content

Instantly share code, notes, and snippets.

@VB10
Created September 21, 2022 01:03
Show Gist options
  • Save VB10/0a68432a28103f893690be20c7d5edc2 to your computer and use it in GitHub Desktop.
Save VB10/0a68432a28103f893690be20c7d5edc2 to your computer and use it in GitHub Desktop.
Manage your future
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