using<R> static method

R using<R>(
  1. R computation(
    1. BoringArena arena
    )
)

Runs computation with a new BoringArena and releases it afterwards.

If computation returns a Future, the arena is released when that future completes, so async computations can keep using the arena across awaits. Returning a Stream is rejected, because the arena would be released before the stream is listened to; use BoringArena.stream instead.

Implementation

static R using<R>(R Function(BoringArena arena) computation) {
  final arena = BoringArena();
  var releaseLater = false;
  try {
    final result = computation(arena);
    if (result is Future) {
      releaseLater = true;
      return result.whenComplete(arena.releaseAll) as R;
    }
    if (result is Stream) {
      throw ArgumentError.value(
        result,
        'computation',
        'must not return a Stream, use BoringArena.stream instead',
      );
    }
    return result;
  } finally {
    if (!releaseLater) {
      arena.releaseAll();
    }
  }
}