/
ChatRoom.java
87 lines (76 loc) · 2.6 KB
/
ChatRoom.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package blog.typed.javadsl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import akka.typed.ActorRef;
import akka.typed.Behavior;
import akka.typed.javadsl.Actor;
public abstract class ChatRoom {
private ChatRoom() {
}
static interface Command {}
public static final class GetSession implements Command {
public final String screenName;
public final ActorRef<SessionEvent> replyTo;
public GetSession(String screenName, ActorRef<SessionEvent> replyTo) {
this.screenName = screenName;
this.replyTo = replyTo;
}
}
private static final class PostSessionMessage implements Command {
public final String screenName;
public final String message;
public PostSessionMessage(String screenName, String message) {
this.screenName = screenName;
this.message = message;
}
}
static interface SessionEvent {}
public static final class SessionGranted implements SessionEvent {
public final ActorRef<PostMessage> handle;
public SessionGranted(ActorRef<PostMessage> handle) {
this.handle = handle;
}
}
public static final class SessionDenied implements SessionEvent {
public final String reason;
public SessionDenied(String reason) {
this.reason = reason;
}
}
public static final class MessagePosted implements SessionEvent {
public final String screenName;
public final String message;
public MessagePosted(String screenName, String message) {
this.screenName = screenName;
this.message = message;
}
}
public static final class PostMessage {
public final String message;
public PostMessage(String message) {
this.message = message;
}
}
public static Behavior<Command> behavior() {
return chatRoom(new ArrayList<ActorRef<SessionEvent>>());
}
private static Behavior<Command> chatRoom(List<ActorRef<SessionEvent>> sessions) {
return Actor.immutable(Command.class)
.onMessage(GetSession.class, (ctx, getSession) -> {
ActorRef<PostMessage> wrapper = ctx.spawnAdapter(p ->
new PostSessionMessage(getSession.screenName, p.message));
getSession.replyTo.tell(new SessionGranted(wrapper));
List<ActorRef<SessionEvent>> newSessions =
new ArrayList<ActorRef<SessionEvent>>(sessions);
newSessions.add(getSession.replyTo);
return chatRoom(newSessions);
})
.onMessage(PostSessionMessage.class, (ctx, post) -> {
MessagePosted mp = new MessagePosted(post.screenName, post.message);
sessions.forEach(s -> s.tell(mp));
return Actor.same();
})
.build();
}
}