Skip to content

AutoCloseable and using shortcuts #3333

@pauldaustin

Description

@pauldaustin

Motivation

I noticed that most times I was using Flux.using and Mono.using that I was using instances of AutoCloseable. So I added the following methods so I didn't have to pass in a closer each time.

Would it be possible to add the desired solution into the core. If so I can create a pull request.

Desired solution

Flux.using(
  ()-> Files.newInputStream(),
  (in)-> ...
);
class Flux {
  :
// This could go in a shared class. Cached closer so it doesn't need to be created on each call
private static Consumer<AutoCloseable> AUTO_CLOSE = (resource) -> {
   try {
     resource.close();
   } catch (final Exception e) {
     throw new RuntimeException(e);
   }
 }; 

 public static <R extends AutoCloseable, V> Flux<V> using(final Callable<R> resourceSupplier,
   final Function<R, Publisher<V>> action) {
   return Flux.using(resourceSupplier, action, AUTO_CLOSE);
 }
}
class Mono {
  :
private static Consumer<AutoCloseable> AUTO_CLOSE = (resource) -> {
   try {
     resource.close();
   } catch (final Exception e) {
     throw new RuntimeException(e);
   }
 };

 public static <R extends AutoCloseable, V> Mono<V> using(final Callable<R> resourceSupplier,
   final Function<R, Mono<V>> action) {
   return Mono.using(resourceSupplier, action, AUTO_CLOSE);
 }
}

Considered alternatives

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions