Comma separated list with Enumerator

可紊 提交于 2019-12-24 07:38:05

问题


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?


回答1:


I wrote a helper function which does what you want to achieve:

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 }
  }
}

Usage:

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)


来源:https://stackoverflow.com/questions/21965269/comma-separated-list-with-enumerator

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