Is it possible to get a response from event fired through Akka Event Stream (scala)? - scala

In are app, we are quite heavily using Akka Event Stream to handle logic that is not related to the main business flow. Things like: send emails, sync records, etc... All of these events are currently fired and forgotten.
system.eventStream.publish(<event>)
And they are handled by listeners, asynchronously, in most cases.
However, I am now investigating an option of extending class functionality through events system and that, sometimes, requires a return value from an event?
Is it even possible to get some result back from an event? I could not find anything specific in this regard.
Thanks,

It's a feature of event based systems: you know who triggered the event, you don't know who will handle it, nor when (can be asynchronous).
So, the most idiomatic solution, if your listener should generate an answer, is to do it in an asynchronous way. And as such, the listener should send an event with it's answer.
Another way to do it is to bypass the event bus and register you handlers as listeners of your event source (you should handle your self the registe/unregister functions through akka messages and a simple list). And when your event source triggers the listeners, it can do it using the ask pattern.

Related

How to observe UI events with the correct Scheduler with RxJava?

Say I have a generic 'Button' in any kind of modern UI framework (I'm working with Android's right now but the problem is pretty much plaform-agnostic). I can put a listener onto this button to listen for click events. My listener gets notified about click events on the UI-thread. This is a problem from a reactive-point-of-view, more specifically in the context of threading.
I can easily create a Subject for the click events. The Observer would most likely want to do processing on another thread. But I can't easily extract (without hacking or ugly workarounds) the Scheduler's Worker from an .observeOn() operator, for dispatching the event onto the correct Worker.
How do I create an Observable stream from these click events, so that the stream will respect the Scheduling requirements of the .observeOn() operator?
It's not clear to me what exactly the issue is here. ObserveOn puts the events to the specified scheduler, which behind the scenes may end up on different threads for different subscribers. If you want to make sure every subscriber will receive the events exactly on the same thread, you need to have a Scheduler with exactly one backing thread. The easiest way of getting such Scheduler is by wrapping an ExecutorService:
Scheduler s = Schedulers.from(Executors.newSingleThreadedExecutor());
PublishSubject<Event> ps = PublishSubject.create();
Observable<Event> events = ps.observeOn(s);
events.subscribe(...);
events.subscribe(...);
ps.onNext(...);

How can I send event for all mounted tags?

riot.js 2.2
By guides on official site of riot.js I have to call something like
tag.trigger('event_name')
where the tag is the instance of certain listener.
But what must i do to trigger event for all tags?
Has riot.js any implementation for this issue or I have to resolve it manually(by keeping all listeners instances)?
Riot has no implementation of keeping references to all event listeners. So, if you want to execute trigger on them directly, you'll have to implement it yourself.
However, I would recommend to use another solution for notifying multiple event listeners.
If you want to let know multiple tags that an event has occured, you can use a shared observable and handle events on this observable. See this SO question. This way, you don't need to keep refereneces to all event listeners, instead, event listeners need to keep reference to single observable ('event aggregator').
You can also try RiotControl as a shared observable.

Using Commands, Events or Services

When designing an application's back-end you will often need to abstract the systems that do things from the systems that actually do them.
There are elements of this in the CQRS and PubSub design patterns.
By way of example:
A new user submits a registration form
Your application receives that data and pushes out a message saying “hey i have some new user data, please do something with this”
A listener / handler / service grabs the data and processes it
(please let me know if that makes no sense)
In my applications I would usually:
Fire a new Event that a Listener is set up to process Event::fire('user.new', $data)
Create a new Command with the data, which is bound to a CommandHandler new NewUserCommand($data)
Call a method in a Service and pass in the data UserService::newUser($data)
While these are nearly exactly the same, I am just wondering - how do you go about deciding which one to use when you are creating the architecture of your applications?
Fire a new Event that a Listener is set up to process
Event::fire('user.new', $data)
Event pattern implies that there could be many handlers, subscribing to the same event and those handlers are disconnected form the sender. Also event handlers usually do not return information to the sender (because there can be actually many handlers and there is a confusion about whose information to return).
So, this is not your case.
Create a new Command with the data, which is bound to a CommandHandler
new NewUserCommand($data)
Commands are an extended way to perform some operation. They can be dispatched, pipelined, queued etc. If you don't need all that capabilities, why to complicate things?
Call a method in a Service and pass in the data
UserService::newUser($data)
Well, this is the most suitable thing for your case, isn't it?
While these are nearly exactly the same, I
am just wondering - how do you go about deciding which one to use when
you are creating the architecture of your applications?
Easy. From many solutions choose only those, which:
metaphorically suitable (do not use events, where your logic does not look like an event)
the simplest (do not go too deep into the depths of programming theories and methods. Always choose solution, that lowers your project development complexity)
When to use command over event?
Command: when I have some single isolated action with few dependencies which must be called from different application parts. The closest analogue is some editor command, which is accessible both from toolbar and menu.
Event: when I have several (at least in perspective) dependent actions, which may be called before/after some other action is executed. For example, if you have a number of services, you can use events to perform cache invalidation for them. Service, that changes a particular object emits "IChangedObject" event. Other services subscribe to such events and respond to them invalidating their cache.

CQRS - can EventListener invoke Command?

I want to use elements of CQRS pattern in my project. I wonder if i do it right with Command and Events.
The thing that I'm not sure is if event can invoke command. To better show what i want to do I will use diagram and example.
This is an example:
User invoke TripCreateCommand. TripCreateCommandHandler do his job and after success publish TripCreatedEvent.
Now we have two listener to TripCreatedEvent (the order of listener execution does not matter)
First listener (can be execute after the second listener):
for each user in trip.author.friends invoke two Command (the order of commands is important)
PublishTripOnUserWallCommand
SendNewTripEmailNotificationCommand
SendNewTripPlatformNotification
Second listener (can be execute before the first listener):
PublishTripOnUserSocials
And this is sample diagram:
Is this a good way ? Can EventListener invoke Command, or maybe I should do it in some other way ?
Your question is about Mesage Driven Architecture which works together with but otherwise unrelated to CQRS.
Anyway, your diagram is almost correct. The event subscriber/handler (I prefer this terminology) can send new Commands via the service bus, but it's not a rule that you should always do this. I implement quite a lot of functionality directly in the event handler, although probalby would be more clean and reliable to send a new command. It really depends on what I want to do.
Note that the message handlers (commands or events) should not know about other handlers. They should know about the bus and the bus takes care of handling. This means that in your app, the event handlers would take the bus as dependency, create the command and send it via the bus. The event handler itself doesn't know what command handler generated the event and can 'reply' to it.
Usually the commands would be handled independently and you can't guarantee the order (unless they're handled synchronously) so maybe you want the second command to be issued as a result of the first command's handling. Indeed, it can be the case for a Saga.
AFAIK you are talking only about doing things synchronously, so your approach works in this case but it's probably not scalable. Moving to async handling will break this execution flow. However your application can be fine with it, not everyhting needs to be twitter.
A message driven architecture is not that straightforward and for some cases (like you want an immediate response from the backend) it's quite complicated to implement, at least more complicated than with the 'standard' approach. So maybe for those particular cases you might want to do it the 'old' way.
If you're worried about decoupling and testing, you can still design the services as they were message handlers but use them directly, instead of a service bus.
Not sure why you would need Commands for performing the updating the information on the user's wall. Why would you choose not to use a View Model Updater for that task.
Sending an email can be considered a Command but could also easily be viewed as just another View Model update.
Not clear on what the purpose of the SendNewTripPlatformNotification is, so I cannot give any suggestions there...
Some of this could also be a candidate for a Saga. Secondly I'm missing your Domain in the diagram, that is what should be responsible for publishing any events, or do you consider the CommandHandler to be the Domain?

J Olivers Event Store - Saga Help

I am trying to wrap my head around Saga's using Jonathan Olivers EventStore and CommonDomain. I understand how Aggregates are working with the CommonDomain/EventStore but I am stuck on grasping Saga usage. I have read both of Jonathan's Saga's with Event Sourcing Part I & II but sill lost in actual implementation
1) More of observation, when persisting the saga the EventStore is utilizing the Headers to persist the Saga and Commands that need to be sent out and it looks like the Payload is storing the Event that triggered the Saga to "wake up". Wondering reasons for this. Would we never want to store individual commands vs having them all in the header?
1) It seems like the Event that triggered the Saga gets replayed multiple times since the "Transition" method in SagaBase always re-adds the event to uncommitted collection. (Unlike ARs that have an internal Apply method vs public Domain method). Maybe I am not using the Transition method properly
2) Typically the bus that you use with the EventStore will publish Events (I implemented IPublishMessages). If I need my Saga to publish a command there does not seem to be a Send option. Do I need to parse the Headers to grab the commands myself?
I am thinking I am using the CommonDomain / EventStore incorrectly as working with Aggregates was easy but Saga's seem "incomplete" to me. I am assuming its because I am not doing it correctly. Still very new to CQRS. Does anyone have a working example of Saga's using J Olivers Common Domain / Event Store? I think that would clear things up considerably.
[EDIT]
I think I figured it out but would like some input. Saga's really should not be publishing events. They send out commands. Thus on the publish side of things for the EventStore (IPublishMessages) I should first be checking the type of message (AggregateType vs SagaType) For AggregateTypes I can publish Events but for SagaTypes only publish the commands (found in Header). This eliminates the same event (say OrderSubmittedEvent) that triggers the creation of the Saga to not publish it again when persisting the saga.
The commands are put in the headers to be sent on the bus. The EventStore is concerned with the storage of events so the events that caused saga transitions are persisted. Later, when the saga is loaded from the event stream, the events will be passed to the saga's transition method to bring it to the current state.
The transition method serves a dual purpose in the saga implementation. Transition is called to handle incoming messages and to load the saga from peristence. In SagaEventStoreRepository.BuildSaga ClearUncomittedEvents and ClearUndispatchedMessages are called on the saga after the current state is built up thus avoiding duplicate event and command processing.
I haven't personally done this but I would use a separate EventStore instance for my sagas. This would allow for the usage of a separate IPublishMessages implementation to take the commands from the event headers and send them.