0

I'm converting code from Casbah to mongodb-scala-driver, and when it comes to capturing the result of a query, the best I've come up with so far is:

var doc: Option[Document] = None 
collection.find(and(equal("name",name),equal("hobby", hobby))).first().subscribe(
  (result: Document) => doc = Some(result)
)
if (doc.isDefined) {
  // ...
}

I just don't like the look of that. How can I improve it?

gknauth
  • 2,310
  • 2
  • 29
  • 44

1 Answers1

1
  val observer = new Observer[Document] {
    override def onComplete {
      //do something when completed
   }

    override def onError(e: Throwable) {
            //do something when error
    }

    override def onNext(doc: Document) {
        //do some when a record is found
     // and keep your logic here maybe call another function passing 'doc'
     }

  } 
   collection.find(and(equal("name",name),equal("hobby",
         hobby))).first().subscribe(observer)

Or

    def doSome(doc:Document):Unit = {
                 //do something here with 'doc'
    }  
    collection.find(and(equal("name",name),equal("hobby",
    hobby))).first().subscribe(doSome)

You need to think asynchronously, something like javascript with its callbacks.

PS. I did not test the code, it is almost a pseudocode.

regards.

salc2
  • 577
  • 5
  • 14