2015-12-30 65 views
0

我有一個代碼,我在檢查如果一個actor不存在已經我們將創建它,但問題是我的代碼使用未來的OnComplete回調函數和我在一個函數/這樣做高清,我只是想在這裏返回ActorRef是我的代碼如何從akka未來獲取值onComplete回調的成功和失敗塊

def getRegularAdminIndexMongoActor():ActorRef= { 
     var actorRef:ActorRef=null 
    val sel = actorSystem.actorSelection("akka://ActorSystem/user/RegularAdminIndexMongoActor"); 
    val future:Future[ActorRef] = sel.resolveOne().mapTo[ActorRef] 
    future.onComplete { 
      case Success(result)=> 
      if(result != null){ 
      log.info("actor exists" + result) 
      } 
      actorRef=result 
      actorRef 
     case Failure(e)=> 
      log.warn("in failure block actor does not exists" + e) 
      val regularAdminIndexMongoActor=system.actorOf(Props[RegularAdminIndexMongoActor],name = "RegularAdminIndexMongoActor") 
      log.info("created a new one "+regularAdminIndexMongoActor.path.toString()) 
      actorRef=regularAdminIndexMongoActor  
    } 
log.info("whats is in actorRef " + actorRef) 
    actorRef 
     } 

和我打電話這樣

log.info("getting ref"+getRegularAdminIndexMongoActor) 

and the output is 
15:33:39.082 555049 [play-internal-execution-context-1] Global$ INFO - whats in actorRef null 
15:33:39.082 555049 [play-internal-execution-context-1] Global$ INFO - getting ref null 
15:33:39.083 555050 [play-internal-execution-context-1] play INFO - Application started (Dev) 
15:33:39.151 555118 [ForkJoinPool-4-worker-7] Global$ INFO - actor exists Actor[akka://ActorSystem/user/RegularAdminIndexMongoActor#-1022921773] 

代碼我怎樣才能得到實際的ActorRef它給我空,但演員正在創建,我試圖在兩個存儲參考通過調用的onComplete並返回NULL之前做這個

actorRef=result //success block 
actorRef=regularAdminIndexMongoActor //failure block 

,我認爲它的返回值初始化我在我的功能如何解決這個開始變空塊?請幫助我如何實現我想要的ActorRef

+0

像'sel.resolveOne()。mapTo [ActorRef] .recover {情況下T => system.actorOf(道具[RegularAdminIndexMongoActor],name =「RegularAdminIndexMongoActor」)}''會給你'Future [ActorRef]'。如果你需要'ActorRef' - 使用'var's使用阻塞'Await.result(f,timeout)' – dk14

+0

是一個壞主意 - 因爲你的'onSuccess' /'onFailure'在另一個線程中被調用,並且可能會在' getRegularAdminIndexMongoActor'返回 – dk14

回答

0

actorRef是一個var,它將在sel.resolveOne()完成之前得到分配,這可能是在您返回值之前。如果你真的想這樣做,你在做什麼非常方式,可以使用

import scala.concurrent._ 
import scala.concurrent.duration._ 

Await.result(f,Duration(6000,"millis")) 

等待結果將阻塞,直到將來提供或6秒鐘過去了。

現在,像其他人一樣表示這不是一個好主意。

因爲你似乎可以創建非常的演員,你可以訪問孩子直接

val child = child(name) 
child.getOrElse(getContext().actorOf(..., name)) 
相關問題