useCancellableFuture<T> function

AsyncSnapshot<T> useCancellableFuture<T>(
  1. Future<T> block(
    1. CancellationToken token
    ),
  2. List<Object?> keys
)

A hook that consumes a cancellable Future and returns its result as an AsyncSnapshot.

The block function receives a CancellationToken that can be used to check if the operation should be cancelled. When the widget is unmounted or the keys change, the token is cancelled, setting token.isCancelled to true.

This is useful for async operations that need to be cancelled when the widget is disposed or when dependencies change.

Returns an AsyncSnapshot that represents the current state:

Example:

class MyWidget extends HookWidget {
  final String userId;
  MyWidget({required this.userId});

  @override
  Widget build(BuildContext context) {
    final snapshot = useCancellableFuture(
      (token) async {
        final data = await fetchUserData(userId);
        if (token.isCancelled) return null; // Bail early if cancelled
        return processData(data);
      },
      [userId],
    );

    return snapshot.mapOrElse(
      ok: (data) => Text('Data: $data'),
      err: (error) => Text('Error: $error'),
      pending: () => CircularProgressIndicator(),
    );
  }
}

Implementation

AsyncSnapshot<T> useCancellableFuture<T>(
  Future<T> Function(CancellationToken token) block,
  List<Object?> keys,
) {
  return useObservable(() => fromCancellableFuture(block), keys);
}