Skip to content

Instantly share code, notes, and snippets.

@volgar1x
Last active August 29, 2015 14:05
Show Gist options
  • Save volgar1x/1b3c4920aac3d93c9aa5 to your computer and use it in GitHub Desktop.
Save volgar1x/1b3c4920aac3d93c9aa5 to your computer and use it in GitHub Desktop.
@Singleton
public class MyService extends FsmService {
@RequiredArgsConstructor
static class Started {
final Map<Class<?>, Map<Integer, Object>> objects;
}
@RequiredArgsConstructor
static class Find {
final Class<?> klass;
final int id;
}
@Inject public MyService(EventBus eventBus) {
super(eventBus);
}
@Override public Optional<Class<? extends Service>> dependsOn() {
return Optional.empty();
}
public Future<T> find(Class<T> klass, int id) {
return emit(new Find(klass, id))
.map(x -> x.get(0))
.map(klass::cast);
}
@FsmInit
@FsmFrom(Stop.class)
@Init void init() {
}
@FsmFrom(Init.class)
@Start Started start() {
return new Started(this.loadObjects());
}
@FsmFrom(Start.class)
@Stop void stop() {
}
@FsmListen Object doFind(Started state, Find action) {
Map<Integer, Object> objects = state.objects.get(action.klass);
if (objects == null) {
throw new NoSuchElementException();
}
Object object = objects.get(action.id);
if (object == null) {
throw new NoSuchElementException();
}
return object;
}
}
Injector injector = ...;
ServiceContext ctx = ...;
MyService myService = injector.getInstance(MyService.class);
myService.start(ctx);
myService.find(Breed.class, 1)
.onSuccess(feca -> {
println(feca.getFullName());
})
.respond(x -> myService.stop(ctx))
;
object MyService {
case object Init
case object Start
case object Stop
case class Find(klass: Class[_], id: Int)
def Find[T: ClassTag](id: Int) = Find(classTag[T].runtimeClass, id)
}
class MyService extends Actor {
type Objects = Map[Class[_], Map[Int, AnyRef]]
private def loadObjects() = ???
def receive = initialized
def initialized: Receive = {
case Start => become(started(this.loadObjects()))
}
def started(objects: Objects): Receive = {
case Stop => become(stopped)
case Find(klass, id) =>
for {
subobj <- objects.get(klass)
obj <- subobj.get(id)
} yield obj
}
def stopped: Receive = {
case Init => become(initialized)
}
}
import MyService._
implicit val timeout = Timeout(5 seconds)
val system: ActorSystem = ???
val myService = system.actorOf(Props[MyService])
myService ! Init
myService ! Start
val resp = (myService ? Find[Breed](1)) map (_.asInstanceOf[Breed])
for (feca <- resp) {
println(feca.fullName)
}
resp onComplete { _ => myService ! Stop }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment