4

Assume we depend on Reactor 3 (i.e in a Spring 5 application) and a text file my/file.txt.

I need to subscribe to the text file lines (both existing ones and those that will appear in the future) and create a Flux<String>. If you wish, neglect blocking IO reads concerns, let's just reveal the principle of building such subscription.

For simplicity assume that we print those lines to std output:

flowLinesFrom(Path.of("my/file.txt"))
   .subscribe(System.out::println);     

What is the proper way to implement Flux<String> flowLinesFrom(Path)?

diziaq
  • 6,881
  • 16
  • 54
  • 96
  • Implement some `tail -f` functionality (Lots of resources on different way to do it), pass the lines to a `processor` (or use `generate`) – 123 May 28 '20 at 08:01

1 Answers1

2

You can use this like so

//Create FluxTailer
FluxTailer tailer = new FluxTailer(
    //The file to tail
    Path.of("my/file.txt").toFile(),
    //Polling interval for changes
    Duration.ofSeconds(1)
);

//Start tailing
tailer.start();

//Subscribe to the tailer flux
tailer.flux().subscribe(System.out::println);

//Just for demo you wait for 10 seconds
try{
    Thread.sleep(10000);
}catch (Exception e){}

//Stop the tailer when done, will also complete the flux
tailer.stop();

You can start stop as you please and also set to read from start or end of file using

tailer.readFromStart();
tailer.readFromEnd();
123
  • 10,778
  • 2
  • 22
  • 45