繁体   English   中英

了解mongodb Scala src中的含义和订阅

[英]Understanding implicits and subscribe in mongodb Scala src

我正在努力更好地了解Scala MongoDB src

使用scala mongodb驱动程序(api doc: http//mongodb.github.io/mongo-scala-driver/

我用的时候

  val collection: MongoCollection[Document] = database.getCollection("mycollection");

      val observable: Observable[Completed] = collection.insertOne(doc)


      observable.subscribe(new Observer[Completed] {
        override def onNext(result: Completed): Unit = println("Inserted")
        override def onError(e: Throwable): Unit = println("Failed")
        override def onComplete(): Unit = println("Completed")
      })

这是隐式方法吗?

/**
     * Subscribes to the [[Observable]] and requests `Long.MaxValue`.
     *
     * Uses the default or overridden `onNext`, `onError`, `onComplete` partial functions.
     *
     * @param doOnNext anonymous function to apply to each emitted element.
     * @param doOnError anonymous function to apply if there is an error.
     * @param doOnComplete anonymous function to apply on completion.
     */
    def subscribe(doOnNext: T => Any, doOnError: Throwable => Any, doOnComplete: () => Any): Unit = {
      observable.subscribe(new Observer[T] {
        override def onSubscribe(subscription: Subscription): Unit = subscription.request(Long.MaxValue)

        override def onNext(tResult: T): Unit = doOnNext(tResult)

        override def onError(throwable: Throwable): Unit = doOnError(throwable)

        override def onComplete(): Unit = doOnComplete()

      })
    }

src: https//github.com/mongodb/mongo-scala-driver/blob/master/driver/src/main/scala/org/mongodb/scala/ObservableImplicits.scala

来自:

 /**
   * Request `Observable` to start streaming data.
   *
   * This is a "factory method" and can be called multiple times, each time starting a new [[Subscription]].
   * Each `Subscription` will work for only a single [[Observer]].
   *
   * If the `Observable` rejects the subscription attempt or otherwise fails it will signal the error via [[Observer.onError]].
   *
   * @param observer the `Observer` that will consume signals from this `Observable`
   */
  def subscribe(observer: Observer[_ >: T]): Unit

src: https//github.com/mongodb/mongo-scala-driver/blob/master/driver/src/main/scala/org/mongodb/scala/Observable.scala

似乎调用subscribe调用了一个新线程(因为它被称为subscribe)但是我没有看到从src调用这个新线程的位置?

当我使用observable.subscribe(new Observer[Completed] {....时,Implicits用于实现调用隐式订阅方法的“连线” observable.subscribe(new Observer[Completed] {....

更新:

使用此代码:

import org.mongodb.scala.MongoClient;
import org.mongodb.scala.bson.collection.immutable.Document;
import org.mongodb.scala._
import org.scalatest._
import Matchers._
import org.mongodb.scala._

class MongoSpec extends FlatSpec with Matchers {

  "Test MongoDb" should "insert" in {
    {
      val mongoClient: MongoClient = MongoClient()
      val database: MongoDatabase = mongoClient.getDatabase("scala-poc");

      val doc: Document = Document("_id" -> 6, "name" -> "MongoDB", "type" -> "database",
        "count" -> 1, "info" -> Document("x" -> 203, "y" -> 100))

      val collection: MongoCollection[Document] = database.getCollection("documents");

      val observable: Observable[Completed] = collection.insertOne(doc)

      observable.subscribe(new Observer[Completed] {
        override def onNext(result: Completed): Unit = println("Inserted")
        override def onError(e: Throwable): Unit = println(" \n\nFailed " + e + "\n\n")
        override def onComplete(): Unit = println("Completed")
      })

      mongoClient.close();

    }

  }
}

导致以下异常:

Failed com.mongodb.MongoClientException: Shutdown in progress

mongoClient.close(); 在insertOne方法完成之前调用。

那么insertOne或subscribe方法是异步的?

  1. 不, subscribe(doOnNext, doOnError, doOnComplete)调用subscribe(observer) (正如您在问题中引用的实现中所看到的)。 所以,如果从那里调用它,你将获得无限循环。 当你写一些像observer.subscribe(x => println(s"next = $x"), error => error.printStackTrace(), () => {})时,会使用“接线”。

  2. 不, subscribe不会创建新线程。 实现Observable类主要是从Java MongoDB驱动程序中包装类并调用它们自己的subscribe方法,例如override def subscribe(observer: Observer[_ >: TResult]): Unit = observe(wrapped).subscribe(observer) 这些subscribe方法也不会启动新线程:请参阅https://mongodb.github.io/mongo-java-driver/3.1/driver-async/reference/observables/以获得一些解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM