Overloaded method value [subscribe] cannot be applied

时间:2016-10-20 12:42:20

标签: mongodb scala

I'm trying to load some values from MongoDB, then serve them as JSON through some controller action. I'm getting the error:

Overloaded method value [subscribe] cannot be applied to  
(
  org.mongodb.scala.bson.collection.immutable.Document => Unit,
  Throwable => Unit,
  () => Unit
)

Though to me everything looks like it should be working.

Here is my controller:

package controllers

import play.api.mvc._
import org.mongodb.scala.bson.collection.immutable.Document
import data.NoteStore

class NotesController extends Controller {

  def index = Action {
    NoteStore.find.subscribe(
      (note: Document) => println(note.toJson),
      (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
      () => println("Done") 
    )
  }
}

And NoteStore:

package data

import org.mongodb.scala.model.Filters._

object NoteStore extends MongoStore {
  def find = {
    db("note-io").find
  }

  def findOne(id: Long) = {
    db("note-io").find(equal("id", id)).first
  }
}

To me it looks like the arguments I have passed to subscribe are incorrect ? But looking online I can't work out why, it looks right to me.

1 个答案:

答案 0 :(得分:1)

Looking at the documentation MongoCollection.find returns an Observable which has subscribe methods with following signatures,

def subscribe(observer: Observer[_ >: TResult]): Unit

// and

def subscribe(observer: com.mongodb.async.client.Observer[_ >: TResult]): Unit

Which clearly shows that you are providing wrong parameters. As it required an Observer.

collection.find().subscribe(
    new Observer[Document](){
      override def onSubscribe(subscription: Subscription): Unit = {
        // probably some logging or something else that you want on subscription
      }

      override def onNext(document: Document): Unit = println(document.toJson())

      override def onError(e: Throwable): Unit = println(s"Error: $e")

      override def onComplete(): Unit = println("Completed")
    }
)