using<T, R> static method

Stream<T> using<T, R>({
  1. required FutureOr<R> resourceFactory(),
  2. required Stream<T> streamFactory(
    1. R
    ),
  3. required FutureOr<void> disposer(
    1. R
    ),
})

When listener listens to it, creates a resource object from resource factory function, and creates a Stream from the given factory function and resource as argument. Finally when the stream finishes emitting items or stream subscription is cancelled (call StreamSubscription.cancel or Stream.listen(cancelOnError: true)), call the disposer function on resource object.

The UsingStream is a way you can instruct an Stream to create a resource that exists only during the lifespan of the Stream and is disposed of when the Stream terminates.

Marble diagram

Example

Rx.using<int, Queue<int>>(
  resourceFactory: () => Queue.of([1, 2, 3]),
  streamFactory: (r) => Stream.fromIterable(r),
  disposer: (r) => r.clear(),
).listen(print); // prints 1, 2, 3

Implementation

static Stream<T> using<T, R>({
  required FutureOr<R> Function() resourceFactory,
  required Stream<T> Function(R) streamFactory,
  required FutureOr<void> Function(R) disposer,
}) =>
    UsingStream(
      resourceFactory: resourceFactory,
      streamFactory: streamFactory,
      disposer: disposer,
    );