如何在不实现的情况下使用源队列并将其返回给调用方? [英] How can I use and return Source queue to caller without materializing it?

查看:49
本文介绍了如何在不实现的情况下使用源队列并将其返回给调用方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的Akka流,想知道如何在我的代码中不实现它的情况下使用并返回源队列给调用者?



想象我们有图书馆产生大量异步调用并通过 Source 返回结果。函数看起来像这样

  def findArticlesByTitle(text:String):Source [String,SourceQueue [String]] = {

val source = Source.queue [String](100,backpressure)

source.mapMaterializedValue {case queue =>

val url = s http://.....& term = $ text
httpclient.get(url).map(httpResponseToSprayJson [SearchResponse])。map { v =>
v.idlist.foreach {id =>
queue.offer(id)
}

queue.complete()
}
}


}

呼叫者可能会这样使用

  //在某处有隐式ActorMaterializer 
val stream = plugin.findArticlesByTitle(title)
val结果= stream.runFold(List [String]()) (((结果,文章)=>文章::结果)

当我在 mapMaterializedValue 不会执行。



我不明白为什么我不能访问 SourceQueue 实例调用者决定如何实现源。



我应如何实现此目标?

解决方案

在您的代码示例中,您将返回源而不是返回值 source.mapMaterializedValue (方法调用不会使Source对象发生突变)。 / p>

I'm trying to use new Akka streams and wonder how I can use and return Source queue to caller without materializing it in my code ?

Imagine we have library that makes number of async calls and returns results via Source. Function looks like this

def findArticlesByTitle(text: String): Source[String, SourceQueue[String]] = {

  val source = Source.queue[String](100, backpressure)

  source.mapMaterializedValue { case queue =>

    val url = s"http://.....&term=$text"
    httpclient.get(url).map(httpResponseToSprayJson[SearchResponse]).map { v =>
      v.idlist.foreach { id =>
        queue.offer(id)
      }

      queue.complete()
    }
  }

  source
}

and caller might use it like this

// There is implicit ActorMaterializer somewhere
val stream = plugin.findArticlesByTitle(title)
val results = stream.runFold(List[String]())((result, article) => article :: result)

When I run this code within mapMaterializedValue is never executed.

I can't understand why I don't have access to instance of SourceQueue if it should be up to caller to decide how to materialize the source.

How should I implement this ?

解决方案

In your code example you're returning source instead of the return value of source.mapMaterializedValue (the method call doesn't mutate the Source object).

这篇关于如何在不实现的情况下使用源队列并将其返回给调用方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆