[英]What Akka Java classes to implement Future callbacks with?
Akka Java在這里。 我的課程:
class SomeActor extends UntypedActor {
// ...
}
class SomeMessage {
// ...
}
// Inside onReceive method for another actor:
Future<Fizz> fizzFut = Patterns.ask(someActor, someMsg, 500)
fizzFut.onComplete(new FizzHandler())
class FizzHandler extends akka.dispatch.OnComplete<Fizz> {
@Override
void onComplete(Throwable error, Fizz result) {
if(error != null) {
// Handle error.
} else {
// Handle success.
}
// TODO: Now how do I send a message back "inside" the
// actor system?
}
}
在運行時,我得到以下異常:
[ERROR] [08/23/2015 05:55:09.490] [myapp-akka.actor.default-dispatcher-4]
[akka://myapp/user/AnotherActor] No signature of method:
scala.concurrent.impl.Promise$DefaultPromise.onComplete() is applicable for argument
types: (com.me.myapp.FizzHandler) values: [<function1>]
Possible solutions: onComplete(scala.Function1, scala.concurrent.ExecutionContext),
isCompleted(), complete(scala.util.Try), tryComplete(scala.util.Try)
所以我嘗試實現了一個scala.Function
子類,但顯然該類是final
,無法擴展。
這里有兩個問題:
onComplete
處理程序使用的Java API類。 有任何想法嗎?; 和 FizzHandler#onComplete(...)
方法正在運行,我如何在我的演員系統“內部”發回消息? Inbox
? 使用Akka 2.3.8和scala 2.10 :
我使用單獨的 onFailure
和onSuccess
方法,分別采用akka.dispatch.OnFailure
和akka.dispatch.OnSuccess<T>
。 例如:
future.onFailure(new OnFailure() {
@Override
public void onFailure(Throwable failure) throws Throwable {
// handle failure
}
}, context().dispatcher());
和
future.onSuccess(new OnSuccess<Object>() {
@Override
public void onSuccess(Object result) throws Throwable {
// handle successful value return
}
}, context().dispatcher());
(如果你在演員之外打電話給你,你必須改變調度員的位置)
在使用onComplete的示例中,您缺少調度程序。 onComplete接受2個參數 - handler
函數和dispatcher
handler
,它應該用於在准備就緒后運行回調。 所以固定樣本是:
import akka.actor.ActorSystem;
import akka.dispatch.Futures;
import akka.dispatch.OnComplete;
import scala.concurrent.Future;
import scala.runtime.BoxedUnit;
final ActorSystem sys = ActorSystem.create();
final Future<String> successful = Futures.successful("");
successful.onComplete(new OnComplete<String>() {
@Override
public void onComplete(Throwable failure, String success) throws Throwable {
}
}, sys.dispatcher());
請注意,一旦Scala 2.12命中它的穩定版本並且Akka使用它(很快)編譯它將以兼容的方式使用Java lambda表達式發出FunctionN
類,然后您將能夠編寫onComplete(d -> {}, dispatcher)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.