tryWith<T extends AutoCloseable> function

Future<void> tryWith<T extends AutoCloseable>(
  1. T resource,
  2. TryWithAction<T> action
)

Utility for automatically closing a resource after use.

Ensures that the resource is closed using resource.close() regardless of whether the action throws or completes normally.

This is similar in spirit to Java's try-with-resources construct.

Example usage:

class MyFile extends AutoCloseable {
  Future<void> write(String content) async {
    print('Writing: $content');
  }

  @override
  Future<void> close() async {
    print('File closed');
  }
}

void main() async {
  final file = MyFile();
  await tryWith(file, (f) async {
    await f.write('Hello, world');
  });
  // Output:
  // Writing: Hello, world
  // File closed
}

Implementation

Future<void> tryWith<T extends AutoCloseable>(T resource, TryWithAction<T> action) async {
  try {
    await action(resource);
  } finally {
    await resource.close();
  }
}