1

I have the following snippet and it generates Flowable<String>. I'm not sure how can I make the Files.lines Autoclosable. I needed to pass in iterator as the second argument to read line one by one as its consumed.

Please note that I have not used the third argument (disposeState) as in generate(Callable<S> initialState, BiConsumer<S,Emitter<T>> generator, Consumer<? super S> disposeState) because there is no point in passing iterator as disposeState.

private Flowable<String> generateFlowable(File file) {
    return Flowable.generate(
            () -> Files.lines(Paths.get(file.toURI()), StandardCharsets.UTF_8).iterator(),
            (iterator, emitter) -> {
                if (iterator.hasNext()) {
                    emitter.onNext(iterator.next());
                } else {
                    emitter.onComplete();
                }
            }
    );
}

The lines are consumed and parsed one by one in the other method. When I did run lsof I found that the handler was not closed. Can some suggest me how could we do that?

Panch
  • 1,097
  • 3
  • 12
  • 43

1 Answers1

1

There are two possible ways to automatically close the Flowable. The first one is utilizing Flowable::using:

private Flowable<String> generateFlowable(File file) {
  return Flowable.using(
          () -> Files.lines(file.toPath(), StandardCharsets.UTF_8),
          stream -> Flowable.fromIterable(stream::iterator),
          Stream::close
  );
}

The second one is using Flowable::generate but does use BufferedReader:

private Flowable<String> generateFlowable(File file) {
  return Flowable.generate(
          () -> Files.newBufferedReader(Paths.get(file.toURI()), StandardCharsets.UTF_8),
          (reader, emitter) -> {
            String line = reader.readLine();
            if (line != null) {
              emitter.onNext(line);
            } else {
              emitter.onComplete();
            }
          }, BufferedReader::close);
}
Flown
  • 11,480
  • 3
  • 45
  • 62
  • This does not close the sequence if the downstream cancels the Flowable before it ends. – akarnokd Nov 02 '18 at 12:56
  • @akarnokd Fixe my examples. – Flown Nov 02 '18 at 16:08
  • Thanks, @Flown So, it looks like we should not be able to use `Files.lines` with `Flowable.generate` if we wanted to achieve autoCloseable. I reckon the `Flowable::generate` with `BufferedReader` will suit my case. – Panch Nov 04 '18 at 23:30