Alpakka MongoDB - specify type in MongoSource

天涯浪子 提交于 2019-12-10 11:48:34

问题


I'm currently playing around with Akka Streams and the Alpakka MongoDB connector.

Is it possible to specify the type for MongoSource?

val codecRegistry = fromRegistries(fromProviders(classOf[TodoMongo]), DEFAULT_CODEC_REGISTRY)
  private val todoCollection: MongoCollection[TodoMongo] = mongoDb
    .withCodecRegistry(codecRegistry)
    .getCollection("todo")

I would like to do something like this:

val t: FindObservable[Seq[TodoMongo]] = todoCollection.find()
MongoSource(t) // Stuck here

But I get the following error:

Expected Observable[scala.Document], Actual FindObservable[Seq[TodoMongo]].

I can't find the correct documentation about this part.


回答1:


This is not published yet, but in Alpakka's master branch, MongoSource.apply takes a type parameter:

object MongoSource {
  def apply[T](query: Observable[T]): Source[T, NotUsed] =
    Source.fromPublisher(ObservableToPublisher(query))
}

Therefore, with the upcoming 0.18 release of Alpakka, you'll be able to do the following:

val source: Source[TodoMongo, NotUsed] = MongoSource[TodoMongo](todoCollection.find())

Note that source here assumes that todoCollection.find() returns an Observable[TodoMongo]; adjust the types as needed.

In the meantime, you could simply add the above code manually. For example:

package akka.stream.alpakka.mongodb.scaladsl

import akka.NotUsed
import akka.stream.alpakka.mongodb.ObservableToPublisher
import akka.stream.scaladsl.Source
import org.mongodb.scala.Observable

object MyMongoSource {
  def apply[T](query: Observable[T]): Source[T, NotUsed] =
    Source.fromPublisher(ObservableToPublisher(query))
}

Note that MyMongoSource is defined to reside in the akka.stream.alpakka.mongodb.scaladsl package (like MongoSource), because ObservableToPublisher is a package-private class. You would use MyMongoSource in the same way that you would use MongoSource:

val source: Source[TodoMongo, NotUsed] = MyMongoSource[TodoMongo](todoCollection.find()) 


来源:https://stackoverflow.com/questions/49209062/alpakka-mongodb-specify-type-in-mongosource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!