2

Suppose we need to create a Flux based on contents of a Closeable resource. For clarity say there is a BufferedReader to be converted to Flux<String>.

BufferedReader reader = createReader("my_resource_path");
Flux<String> flux = Flux.fromIterable(() -> iteratorOfLines(reader));

Let us assume that iteratorOfLines produces a finite set of items.

I'm looking for a way to close BufferedReader when either the Flux has consumed all data from it or the remaining data is not needed for some reason (i.e. subscription is aborted).

There's a constructor reactor.core.publisher.FluxIterable(Iterable iterable, Runnable onClose), but:

  1. seems that it is not reachable (even transitively) from public API of reactor
  2. I doubt that it can help, because it does not cover the case when Flux stops before getting the last item in the iterable.

What is the proper way of cleaning/closing resources after Flux.fromIterable publishes the last item?

Probably, there is a better way than fromIterable to do similar things, so all options are welcome.

diziaq
  • 6,881
  • 16
  • 54
  • 96

1 Answers1

3

For an equivalent to try with resources you can use using

    Flux.using(
            //Set up resource
            () -> createReader("my_resource_path"),
            //Create flux from resource
            reader -> Flux.fromIterable(iteratorOfLines(reader)),
            //Perform action (cleanup/close) 
            //when resource completes/errors/cancelled
            reader -> {
                try{
                    reader.close();
                }catch(IOException e){
                    throw Exceptions.propagate(e);
                }
            }
    );
123
  • 10,778
  • 2
  • 22
  • 45
  • 1
    Not sure why this is downvoted - I prefer it to `doFinally()` personally. – Michael Berry Jun 09 '20 at 07:53
  • 1
    I believe this is much cleaner solution in case of working with closeable resources. Seems to me that `doFinally` belongs to a different layer of abstraction, namely - to the publications life-cycle maintenance. – diziaq Jun 09 '20 at 08:10
  • @diziaq Yep, I personally prefer this for any resources since it keeps everything neatly packaged in one place in the chain – 123 Jun 09 '20 at 15:06