Search code examples
javaakkaakka-stream

How to read each new line from file after 10 second delay with Akka?


I am trying to read from file line by line with some delay.

For example:

  • read and print 1st line of the file
  • wait 10 seconds
  • read and print 2nd line of the file
  • etc

So far I have tried something like this:

final Path filePath = Paths.get('path/to/file');
final ActorSystem system = ActorSystem.create();
final Materializer materializer = ActorMaterializer.create(system);

Sink<ByteString, CompletionStage<Done>> printlnSink =
   Sink.<ByteString>foreach(chunk -> System.out.println(chunk.utf8String()));

final CompletionStage<IOResult> result = 
  FileIO.fromPath(filePath)
 .throttle(1, Duration.create(10, TimeUnit.SECONDS), 1, ThrottleMode.shaping())
 .to(printlnSink)
 .run(materializer);

But the this outbursts too many lines at a time and not one line at a time.

Any ideas how to fix it?


Solution

  • final CompletionStage<IOResult> result = 
     .via(Framing.delimiter(ByteString.fromString(System.lineSeparator()),10000,FramingTruncation.ALLOW))
      FileIO.fromPath(filePath)
     .throttle(1, Duration.create(10, TimeUnit.SECONDS), 1, ThrottleMode.shaping())
     .to(printlnSink)
     .run(materializer);
    

    See if that works for you, framing Class documents should clarify