Docs sample of accessing context from persistent behavior

This commit is contained in:
Johan Andrén 2018-09-20 15:45:16 +02:00
parent 68c4e14dbd
commit 5d129a804b
3 changed files with 54 additions and 3 deletions

View file

@ -5,8 +5,10 @@
package akka.persistence.typed.javadsl;
import akka.actor.Scheduler;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.ActorRef;
import akka.actor.typed.javadsl.Behaviors;
import akka.persistence.typed.EventAdapter;
import akka.actor.testkit.typed.javadsl.TestInbox;
import akka.persistence.typed.SideEffect;
@ -266,13 +268,24 @@ public class PersistentActorCompileOnlyTest {
.thenAccept(sender::tell);
}
// #actor-context
public Behavior<Command> behavior(String persistenceId) {
return Behaviors.setup(ctx -> new MyPersistentBehavior(persistenceId, ctx));
}
// #actor-context
// #actor-context
class MyPersistentBehavior extends PersistentBehavior<Command, Event, RecoveryComplete.EventsInFlight> {
// this makes the context available to the command handler etc.
private final ActorContext<Command> ctx;
public MyPersistentBehavior(String persistenceId, ActorContext<Command> ctx) {
super(persistenceId);
this.ctx = ctx;
}
// #actor-context
@Override
public EventsInFlight emptyState() {
@ -307,4 +320,5 @@ public class PersistentActorCompileOnlyTest {
}
}
}
}

View file

@ -432,4 +432,31 @@ object PersistentActorCompileOnlyTest {
}
object WithContext {
sealed trait Command
sealed trait Event
class State
// #actor-context
val behavior: Behavior[String] =
Behaviors.setup { ctx =>
PersistentBehaviors.receive[String, String, State](
persistenceId = "myPersistenceId",
emptyState = new State,
commandHandler = CommandHandler.command {
cmd
ctx.log.info("Got command {}", cmd)
Effect.persist(cmd).thenRun { state =>
ctx.log.info("event persisted, new state {}", state)
}
},
eventHandler = {
case (state, _) state
})
}
// #actor-context
}
}