简体   繁体   中英

Akka wait for stream completion

I'd like to know if it's possible to wait for completion of the following stream. It may be obvious for some people, but I'm new to akka.

final Materializer mat = ActorMaterializer.create(getContext());

String path = "Databases\\" + r.book.db + "\\" + r.book.title + ".txt";
Stream<String> fileStream = Files.lines(Paths.get(path));

Source<StreamResult, NotUsed> lines = Source.from(fileStream
                            .map(e -> new StreamResult(r.replyTo, e))
                            .collect(Collectors.toList()));

lines.throttle(1, Duration.ofSeconds(1))
                            .runWith(Sink.actorRef(sender, new StreamEnd()), mat);

Two things which you need to pay attention here, is that you use Sink (that is the end of the stream definition) and materialised values

Sink.actorRef returns Sink<In,​NotUsed> , so you can't just figure out stream termination information from what you have (because materialised value is NotUsed in your case). Moreover you can't use other sink which provides this info (eg, Sink.ignore , whose materialised value gives you Future about when stream finishes), because in general stream has one sink (of course, you can use Flow.alsoToMat , but there exists better approach)

You can use Flow.watchTermination on the flow just before the last Sink , which will tell you about your upstream status. Probably it makes the most sense because you use Sink.actorRef in the shape of "send and forget".

I don't know your full use case, but just in case maybe you'll find Flow.ask useful. It sends a message to actor as well, but also waits for the actor response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM