用Enumerator逗号分隔的列表 [英] Comma separated list with Enumerator

查看:139
本文介绍了用Enumerator逗号分隔的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在新项目(Scala 2.10.3,Play2 2.2.1,Reactivemongo 0.10.0)中使用Scala,并遇到了一个非常标准的用例,即-将MongoDB中的所有用户流式传输到外部客户.导航枚举器,枚举API之后,我还没有找到一个可靠的解决方案,因此我通过以下方式解决了这个问题:

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

从我的角度来看,这有点棘手-主要是因为我需要在元素列表中添加Json Start Array,Json End Array和逗号分隔符,而我无法将其作为纯Json流提供,所以我将其转换为String steam.

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.

在游戏中使用reactmongo的标准解决方案是什么?

推荐答案

我编写了一个辅助函数,该函数可以实现您想要实现的目标:

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

用法:

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)

这篇关于用Enumerator逗号分隔的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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