2013-05-17 30 views
6

Đây là mã hoạt động. Nó gửi một tin nhắn cho một diễn viên (Greeter) và chờ đợi câu trả lời. Nhưng nó chặn luồng hiện tại.Xử lý Tương lai onSuccess như phản hồi từ một diễn viên Akka

public class Future1Blocking { 

    public static void main(String[] args) throws Exception { 

     ActorSystem system = ActorSystem.create("system"); 
     final ActorRef actorRef = system.actorOf(Props.create(Greeter.class), "greeter"); 

     Timeout timeout = new Timeout(Duration.create(5, "seconds")); 
     Future<Object> future = Patterns.ask(actorRef, Greeter.Msg.GREET, timeout); 

     // this blocks current running thread 
     Greeter.Msg result = (Greeter.Msg) Await.result(future, timeout.duration()); 

     System.out.println(result); 

    } 
} 

Tôi có thể sử dụng ví dụ nào để sử dụng future.onSuccess để nhận kết quả mà không chặn chuỗi cuộc gọi hiện tại?

Trả lời

10

Ahh. đó là dễ dàng (xin lỗi).

future.onSuccess(new PrintResult<Object>(), system.dispatcher()); 

đâu:

public final class PrintResult<T> extends OnSuccess<T> { 
    @Override public final void onSuccess(T t) { 
     System.out.println(t); 
    } 
} 
Các vấn đề liên quan