1

I've just started working with Scala in my new project (Scala 2.10.3, Play2 2.2.1, Reactivemongo 0.10.0), and encountered a pretty standard use case, which is - stream all the users in MongoDB to the external client. After navigating Enumerator, Enumeratee API I have not found a solid solution for that, and so I solved this in following way:

    val users = collection.find(Json.obj()).cursor[User].enumerate(Integer.MAX_VALUE, false)
    var first:Boolean = true
    val indexedUsers = (users.map(u => {
        if(first) {
            first = false;
            Json.stringify(Json.toJson(u))
        } else {
            "," + Json.stringify(Json.toJson(u))
        }
    }))

Which, from my point of view, is a little bit tricky - mainly because I needed to add Json Start Array, Json End Array and comma separators in element list, and I was not able to provide it as a pure Json stream, so I converted it to String steam.

What is a standard solution for that, using reactivemongo in play?

4

1 回答 1

1

我写了一个辅助函数来完成你想要实现的目标:

def intersperse[E](e: E, enum: Enumerator[E]): Enumerator[E] = new Enumerator[E] {
  val element = Input.El(e)

  override def apply[A](i1: Iteratee[E, A]): Future[Iteratee[E, A]] = {
    var iter = i1

    val loop: Iteratee[E, Unit] = {
      lazy val contStep = Cont(step)

      def step(in: Input[E]): Iteratee[E, Unit] = in match {
        case Input.Empty ⇒ contStep
        case Input.EOF ⇒ Done((), Input.Empty)
        case e @ Input.El(_) ⇒
          iter = Iteratee.flatten(iter.feed(element).flatMap(_.feed(e)))
          contStep
      }

      lazy val contFirst = Cont(firstStep)

      def firstStep(in: Input[E]): Iteratee[E, Unit] = in match {
        case Input.EOF ⇒ Done((), Input.Empty)
        case Input.Empty ⇒
          iter = Iteratee.flatten(iter.feed(in))
          contFirst
        case Input.El(x) ⇒
          iter = Iteratee.flatten(iter.feed(in))
          contStep
      }

      contFirst
    }

    enum(loop).map { _ ⇒ iter }
  }
}

用法:

val prefix = Enumerator("[")
val suffix = Enumerator("]")
val asStrings = Enumeratee.map[User] { u => Json.stringify(Json.toJson(u)) }
val result = prefix >>> intersperse(",", users &> asStrings) >>> suffix

Ok.chunked(result)
于 2015-11-20T08:26:40.280 回答