2017-06-14 103 views
2

我已阅读Akka streams materialization concept,并理解流物化是:阿卡流:是什么mapMaterializedValue意味着

,以运行服用流描述(图),并分配它需要的所有必要资源的过程。

我跟着一个例子,使用mapMaterializedValue构建我的akka​​流,将消息发送到队列。代码的目的是推动信息流蓝图后,排队已经建立和代码工作,但我真的不明白是什么mapMaterrializaedValue代码做:

Promise<SourceQueueWithComplete<String>> promise = new Promise.DefaultPromise<>(); 

Source<String, SourceQueueWithComplete<String>> s = Source 
    .queue(100, OverflowStrategy.fail()) 
    .mapMaterializaedValue(queue -> { 
     promise.trySuccess(queue); 
    }); 

source.toMat(Sink.foreach(x -> System.out.println(x)), Keep.left()).run(materIalizer); 

promise.<SourceQueueWithComplete<String>>future().map(mapMapperFunction(), actorSystem.dispatcher()); 

回答

4

mapMaterializedValue目的是在物化后立即转化物化价值。例如,假设你有接受这样的回调第三方库:

interface Callback<T> { 
    void onNext(T next); 
    void onError(Throwable t); 
    void onComplete(); 
} 

然后你就可以创建一个返回Source<T, Callback<T>>其物化价值,你可以立即传递给第三方库的方法时,流实际运行:

<T> Source<T, Callback<T>> callbackSource() { 
    return Source.queue(1024, OverflowStrategy.fail()) 
     .mapMaterializedValue(queue -> new Callback<T> { 
      // an implementation of Callback which pushes the data 
      // to the queue 
     }); 
} 

Source<Integer, Callback<Integer>> source = callbackSource(); 

Callback<Integer> callback = source 
    .toMat(Sink.foreach(System.out::println), Keep.left()) 
    .run(materializer); 

thirdPartyApiObject.runSomethingWithCallback(callback); 

你可以在这里看到,因为你这样做队列这可以简化必须使用这样一种第三方API的代码 - >回调转变只有一次,在一个封装它方法。

然而就你而言,你并不需要它。您正在使用mapMaterializedValue完成与物化价值,这是完全没有必要的外部承诺,因为你可以直接使用它的物化后的物化值:

Source<String, SourceQueueWithComplete<String>> s = Source 
    .queue(100, OverflowStrategy.fail()); 

SourceQueueWithComplete<String> queue = source 
    .toMat(Sink.foreach(x -> System.out.println(x)), Keep.left()) 
    .run(materIalizer); 

mapMapperFunction().apply(queue); 
+1

谢谢弗拉基米尔,mapMaterializedValue的很清楚交代,现在我了解它是如何工作的。关于物化价值的另外一个问题,就像未来? – zt1983811

+2

否;物化价值既不要求为期货(例如,这些例子中的排队不会被作为未来返回,虽然有时候垫价值是未来),也不与期货“相似” - 唯一的这种相似性是mapMaterializedValue'和'Future.map'方法名称中的子字符串'map',这是因为这种转换几乎总是被称为'map'。你可以在我的答案[这里]找到更多关于物化值的内容(https://stackoverflow.com/questions/39727729/akka-streams-what-does-mat-represents-in-sourceout-mat/39729078#39729078)。 –

+0

感谢您的回答,我会看看那篇文章。 – zt1983811