Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

code challenge

By: a guest on May 30th, 2014  |  syntax: Scala  |  size: 1.67 KB  |  views: 294  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package mix
  2.  
  3. /*
  4. Scala 2.10.3
  5. libraryDependencies ++= Seq(
  6.     "com.netflix.rxjava" % "rxjava-scala" % "0.18.3",
  7.     "com.h2database" % "h2" % "1.4.178",
  8. )
  9. */
  10.  
  11. import java.sql.Connection
  12. import java.sql.DriverManager
  13.  
  14. import scala.concurrent.ExecutionContext.Implicits.global
  15. import scala.concurrent.Future
  16. import scala.concurrent.duration.DurationInt
  17.  
  18. import rx.lang.scala.Observable
  19. import rx.lang.scala.Subscription
  20.  
  21. object Partial {
  22.  
  23.   def main(args: Array[String]) {
  24.     Class.forName("org.h2.Driver")
  25.     val conn = DriverManager.getConnection("jdbc:h2:mem:")
  26.     conn.prepareStatement("create table persons (name varchar(100))").execute()
  27.     List("horia", "raluca", "lara", "albert").foreach { p =>
  28.       conn.prepareStatement("insert into persons(name) values('" + p + "')").execute()
  29.     }
  30.     val found = searchPeople("select name from persons", conn)
  31.     conn.close()
  32.     println(found)
  33.   }
  34.  
  35.   def searchPeople(query: String, conn: Connection): List[String] = {
  36.     val five = Observable.interval(3000 millis).take(1)
  37.     val jdbc = Observable[String](subscriber => {
  38.      
  39.       import scala.concurrent.ExecutionContext.Implicits.global
  40.  
  41.       subscriber.add(Subscription {
  42.         Thread.currentThread().interrupt()
  43.       })
  44.      
  45.       Future {
  46.         val rs = conn.prepareStatement(query).executeQuery()
  47.         while (rs.next() && !subscriber.isUnsubscribed) {
  48.           Thread.sleep(1000L)
  49.           subscriber.onNext(rs.getString("name"))
  50.         }
  51.         if (!subscriber.isUnsubscribed) {
  52.           subscriber.onCompleted()
  53.         }
  54.       }
  55.     })
  56.     val max = jdbc.takeUntil(five)
  57.     max.toBlockingObservable.toList
  58.  
  59.   }
  60.  
  61. }