简体   繁体   English

Akka等待流完成

[英]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. 对于某些人来说这可能是显而易见的,但是我是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 (即流定义的末尾)和物化值

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). Sink.actorRef返回Sink<In,​NotUsed>所以你不能仅仅从你所拥有的(因为物化值计算出流终止信息NotUsed你的情况)。 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) 此外,您不能使用其他提供此信息的接收器(例如Sink.ignore ,其物化值将为您提供有关流何时结束的Future ),因为通常流中只有一个接收器(当然,您可以使用Flow.alsoToMat ,但是有更好的方法)

You can use Flow.watchTermination on the flow just before the last Sink , which will tell you about your upstream status. 您可以在最后一个Sink之前的流上使用Flow.watchTermination ,它将告诉您上游的状态。 Probably it makes the most sense because you use Sink.actorRef in the shape of "send and forget". 可能最有意义,因为您以“发送并忘记”的形式使用Sink.actorRef

I don't know your full use case, but just in case maybe you'll find Flow.ask useful. 我不知道您的完整用例,但以防万一,您可能会发现Flow.ask有用。 It sends a message to actor as well, but also waits for the actor response. 它也向参与者发送消息,但也等待参与者的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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