I believe the main idea behind this is to isolate the scope of messages sent to a specific actor. Having typed protocols helps cut down on sending an unexpected Protocol (or message) to the actor. Keeping them in one class is a nice way to capture all the actions related to that specific domain, like EmployeeProtocol helps enforce EmployeeActor to receive expected messages. However, you still have the responsibility to send them correctly:
Here is our controller call to the EmployeeActor using the protocol:
public class EmployeeController extends Controller {
return Promise.wrap(ask(employeeActorRef,
new GetCurrentEmployees(), 5000))
.map(response -> ok((JsonNode)response));
}
}
EmployeeActor processes its messages based on the received protocol:
public class EmployeeActor extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof GetCurrentEmployees) {
//do things related to this task
} else if (message instanceof CreateNewEmployee) {
//do things related to this task
} else if (message instanceof RemoveEmployee) {
//do things related to this task
}
}
}
Here protocols are defined for actions on the employee and can hold typed fields so we know what to expect. The fact that we use static final fields in the protocol will enforce immutability of the messages:
public class EmployeeProtocol {
public static class GetCurrentEmployees {}
public static class CreateNewEmployee {
private final String name;
public CreateNewEmployee(String name) {
this.name = name;
}
//getter
}
public static class RemoveEmployee {
public final String uuidToRemove;
public RemoveEmployee(String uuidToRemove) {
this.uuidToRemove = uuidToRemove;
}
//getter
}
}
Akka-Typed is being developed in akka scala which can be used to send messages of only a specific type so that if you attempt to send an incorrect message type the compiler will complain. Akka-typed - http://doc.akka.io/docs/akka/snapshot/scala/typed.html#typed-scala
Maybe they wanted us to use this best practice because we'll be able to make it type safe in the future... There was also mention of this coming to java here in this podcast: https://www.typesafe.com/resources/video/akka-2-4-plus-new-commercial-features-in-typesafe-reactive-platform