2013-02-07 66 views
0

我想從我的Scala應用程序中使用AsyncTwitter。有沒有辦法把它包裝在期貨中,所以看起來更像是慣用的斯卡拉?或者期貨真的在那裏將同步事物轉換爲異步事件(即對已經是異步的函數沒有用處)?從Scala異步使用twitter4j

無論哪種方式,什麼是在斯卡拉

  1. 裹做一個異步的Twitter狀態更新在期貨AsyncTwitter代碼的最地道的方式是什麼?
  2. 包裝未來的同步代碼?
  3. 忘記期貨,只是在Scala中重寫下面的代碼。

和(特別是如果#1是答案)最終的代碼是什麼樣子?

這裏是我想了解一下代碼:http://twitter4j.org/en/code-examples.html#asyncAPI

TwitterListener listener = new TwitterAdapter() { 
    @Override public void updatedStatus(Status status) { 
     System.out.println("Successfully updated the status to [" + 
       status.getText() + "]."); 
    } 

    @Override public void onException(TwitterException e, int method) { 
     if (method == TwitterMethods.UPDATE_STATUS) { 
     e.printStackTrace(); 
     } else { 
     throw new AssertionError("Should not happen"); 
     } 
    } 
} 
// The factory instance is re-useable and thread safe. 
AsyncTwitterFactory factory = new AsyncTwitterFactory(listenrer); 
AsyncTwitter asyncTwitter = factory.getInstance(); 
asyncTwitter.updateStatus(args[0]); 

我猜#2是不是答案,因爲那時你還是堅持了同步線程的掛在頭頂懸掛,對?

回答

1

使用Scala的期貨應該是這樣的(例子是getDirectMessages)的實現:

class DirectMessageListener extends TwitterAdapter { 

    val promise = Promise[Seq[DirectMessage]]() 


    override def gotDirectMessages(messages: ResponseList[DirectMessage]) { 
    promise.success(messages) 
    } 

    override def onException(te: TwitterException, method: TwitterMethod) { 
    promise.failure(te) 
    } 
} 

class TwitterClient(twitter: Twitter) { 

    val factory = new AsyncTwitterFactory() 

    def getDirectMessage(): Future[Seq[DirectMessage]] = { 
    val listener = new DirectMessageListener 
    val asyncTwitter = factory.getInstance(twitter) 
    asyncTwitter.addListener(listener) 
    asyncTwitter.getDirectMessages() 
    listener.promise.future 
    } 

} 

用法:

val client = new TwitterClient(???) 
client.getDirectMessage() onComplete (_.foreach(println))