using<T, R> static method

Single<T> using<T, R>(
  1. R resourceFactory(),
  2. Single<T> singleFactory(
    1. R
    ),
  3. FutureOr<void> disposer(
    1. R
    )
)

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

This method is a way you can instruct a Single to create a resource that exists only during the lifespan of the Single and is disposed of when the Single terminates.

The returned Single is single-subscription Stream.

Marble diagram

Example

class Resource {
  void close() => print('Closed');
  int get value => 0;
}

RxSingles.using<int, Resource>(
  () => Resource(),
  (r) => Single.value(r.value),
  (r) => r.close(),
).listen(print); // prints 0, Closed

See Rx.using and UsingStream.

Implementation

static Single<T> using<T, R>(
  R Function() resourceFactory,
  Single<T> Function(R) singleFactory,
  FutureOr<void> Function(R) disposer,
) =>
    Single.safe(
      Rx.using(
        resourceFactory,
        singleFactory,
        disposer,
      ),
    );