Lets assume I have a PersistentEntity whose command/event/state can be modeled by the following case class:
case class MyCommand(number: Int)
case class MyEvent(number: Int)
case class MyState(maxNumber: Int)
The entity should do a simple thing, keep the highest number it encountered so far.
What an entity does when receiving MyCommand is to generate MyEvent, which in turn updated MyState if number > maxNumber
.
I would like to expose that state via read side, and from what I understand (I’m still a newbie when it comes to Lagom), in my implementation of ReadSideProcessor[MyEvent]
I should describe how to react on those events via ReadSideHandler[MyEvent]
.
But the problem is that can only react on event changes, while I would like it to react when my state changes.
This leads me to think I should expose my state changes as events as well.
I was thinking how to do that, and what first came to my mind seems like an anti-pattern:
In MyCommand handler, also persist an event MyEvent2(maxNumber), where I have to calculate it from current state and number in MyCommand. The issue I see here is that the same business logic that takes place in MyEvent handler will take place here as well. I kinda don’t like that too much.
This is effectively calculating new state in Command handler and persisting entity state as such, which seems like an anti-pattern to me. This may be a simple example, but the real world scenarios might not be.
I’ve seen the blog example on Lagom docs, but the thing is that my state is, in lack of a better word, destructive. And it may be heavy to calculate, so I don’t want to do that in more than one place (entity).
I know Lagom snapshots entity state every now and then, when it deems it right, and I was wondering if I could do the same in some fashion.
I hope I didn’t complicate the example much :)