boost msm library newbi in firing events - boost

When we call fsm.process_event('eventname');
is there a way to return true if the transition occured and false if "no_transition" was called or an exception occurred?
Thanks

Seeing as no one has answered so far I'll post my quite humble suggestion. You could try calling the current_state() method before and after calling fsm.process_event() and compare the results. This however would not cover the case of self transitions or internal transitions and is not something I would use if there are other alternatives (its a hack at best).
If you are trying to catch the case of an event not being handled by any state and just propagating through you could add one more bottom layer superstate which reports events that reach it (i.e. are ignored by all states they propagated through).
I have had situations where I needed to know if some event actually did something and when it did it (maybe it was deferred first and then executed). In that case I made my MSM post "ACK" messages to an outside queue, I'm not sure if this applies to your problem.
In my humble knowledge interrupts and state machines don't mix very well, I usually either simply swallow them or try and turn them into some event depending on the context. You should never allow you sates (the underlying function objects) to throw.

Related

What is *like* a promise but can resolve mutliple times?

I am looking for a pub/sub mechanism that behaves like a promise but can resolve multiple times, and behaves like an event except if you subscribe after a notification has happened it triggers with the most recent value.
I am aware of notify, but deferred.notify is order-sensitive, so in that way it behaves just like an event. eg:
d.notify('notify before'); // Not observed :(
d.promise.progress(function(data){ console.log(data) });
d.notify('notify after'); // Observed
setTimeout(function(){ d.notify('notify much later') }, 100); // Also Observed
fiddle: http://jsfiddle.net/foLhag3b/
The notification system I'd like is a good fit for a UI component that should update to reflect the state of the data behind it. In these cases, you don't want to care about whether the data has arrived yet or not, and you want updates when they come in.
Maybe this is similar to Immediate mode UIs, but is distinct because it is message based.
The state of the art for message based UI updating, as far as I'm aware, is something which uses a promise or callback to initialize, then also binds an update event:
myUIComponent.gotData(model.data);
model.onUpdate(myUIComponent.gotData); // doing two things is 2x teh workz :(
I don't want to have to do both. I don't think anyone should have to, the use case is common enough to abstract.
model.whenever(myUIComponent.gotData); // yay one intention === one line of code
I could build a mechanism to do what I want, but I wanted to see if a pub/sub mechanism like this already exists. A lot of smart people have done a lot in CS and I figure this concept must exist, I just am looking for the name of it.
To be clear, I'm not looking to change an entire framework, say to Angular or React. I'm looking only for a pub/sub mechanism. Preferably an implementation of a known concept with a snazzy name like notifr or lemme-kno or touch-base.
You'll want to have a look at (functional) reactive programming. The concept you are looking for is known as a Behavior or Signal in FRP. It models the change of a value over time, and can be inspected at any time (continuously holds a value, in contrast to a stream that discretely fires events).
var ui = state.map(render); // whenever state updates, so does ui with render() result
Some popular libraries in JS are Bacon and Rx, which use their own terminology however: you'll find properties and observables.

Functional Event Driven Programming

I'm having trouble writing event driven GUI code in a functional style, using Clojure and Seesaw. Specifically, I can't figure out how to pass the state of the program around without using globals, or some other unpleasant hack. My current approach is something like this:
(defn event-handler [gui-state event]
(update-gui! (get-new-state gui-state event)))
(defn update-gui! [gui-state]
(remove-all-listeners (gui-state :button))
(seesaw.core/listen (gui-state :button)
:action
(partial event-handler gui-state)))
It sets an event listener on the relevant component, with a partially applied function to advance the state and update the gui, including removing the old listener. Although this seems to be working, I don't really like it, partly because I can't pass the listener itself in the state (since it's not constructed until after I've already defined the state), so removing the old listener requires removing all listeners, which could cause problems as the program grows.
The closest solution I've found online is in this answer, but I don't know how to handle events as a stream like it shows. I'm sure there must be a better solution than my current approach, but I can't figure out what.
Can anyone show me how I can respond to user input events while still following a functional style?
The Streams from the linked answer seem like an analog of core.async channels.
Instead of removing all listeners each event maybe pass in a channel that has event details put to it. The same channel should go to the button's logic handler where it will repeatedly be taken from.

Eventbus event order

Morning,
I'm using the SimpleEvent bus to send data from my centralized data reviver to the Widgets. This works really fine, I get one set of new Data form the server, the success method of the RPC call puts it on the Eventbus, each widget looks if the data is for it, if yes it 'displays' it, if not, it does nothing.There is only one data set per request and the widgets don't depend on other data being already sent.
Now I have a Tree widget. The child nodes of the Tree are created throw this data sets too, and this child nodes register itself to the Eventbus to revive the data for their child nodes. The data shall be received in on rush (for performance reasons obv), so I will get multiple data sets which are put on the Eventbus at the 'same time' (in a for loop). I only control the order in which they are put there (first the root, then the data for the first child......). How does the Eventbus now proceeds the events?
Does he wait till the first event is completed, so the first child of
the tree already finished creation and register itself to the
Eventbus, to revive the data to create it's child's.
Does he handle them simultaneous, so a widget isn't even registered to the Eventbus.
Does he mix up the order?!?!
Current solution approaches:
The best solution I can think of, is to only put new events on the
Eventbus when the previous got completed. However I found a method
which does so, or if it is the standard behavior of the Eventbus .
Fire a request processing finished event, when a event was processed by a widget. Yucks... this leads to a lot of additional code and causes big problems, when data is put on the Eventbus which doesn't belong to any widget....
Register a static variable which is set to true when the request got handled and the Eventbus waits this long till he puts the next request on the Eventbus (Quiet similar to two, but way worse coding style and the same problems)
All events are handled by the root tree element, which sends them upwards to the respective child's.
Which solution would you prefer and why?
Regards,
Stefan
PS: my favorite answer would be that 1. is the standard behavior of the Eventbus^^
PPS: The solution should also be working on when introducing Webworkers.
The EventBus#fireEvent is synchronous. It's by design. You can pass an event to the bus, have handlers possibly modify it, and when execution returns to your method you can check the event; this is used for PlaceChangeRequestEvent and its setMessage for instance.
FYI, if a handler throws an exception, it won't prevent other handlers from being executed. The fireEvent will then wrap the exceptions (plural; several handlers can throw) in an UmbrellaException.
Although EventBus is a nice way of de-coupling parts of your application it doesn't mean it should be "overused".
I also think you should be careful not to circumvent the asynchronous behavior of your client-side code by introducing synchronous/blocking like behavior.
Javascript is single threaded so I don't think you can have two events at the same time. They will be executed one after the other.
If you fire an event on the EventBus (i.e. SimpleEventBus) it will just iterator through the list of attached handlers and execute them. If no handler is attached nothing happens.
I personally would prefer the 4th. approach especially if you plan to use a CellTree some time in the future. The Tree widget/CellTree widget handles the event and constructs its structure by traversing through the object.

When to use events?

At work, we have a huge framework and use events to send data from one part of it to another. I recently started a personal project and I often think to use events to control the interactions of my objects.
For example, I have a Mixer class that play sound effects and I initially thought I should receive events to play a sound effect. Then I decided to only make my class static and call
Mixer.playSfx(SoundEffect)
in my classes. I have a ton of examples like this one where I initially think of an implementation with events and then change my mind, saying to myself it is too complex for nothing.
So when should I use events in a project? In which occasions events have a serious advantage over others techniques?
You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.
In your Mixer example, I'd have events signal the start and end of playing of the sound effect. If I were to use this in a desktop application, I could use those events to enable/disable controls in the UI.
The difference between Calling a subroutine and raising events has to do with: Specification, Election, Cardinality and ultimately, which side, the initiator or the receiver has Control.
With Calls, the initiator elects to call the receiving routine, and the initiator specifies the receiver. And this leads to many-to-one cardinality, as many callers may elect to call the same subroutine.
With Events on the other hand, the initiator raises an event that will be received by those routines that have elected to receive that event. The receiver specifies what events it will receive from what initiators. This then leads to one-to-many cardinality as one event source can have many receivers.
So the decision as to Calls or Events, mostly has to do with whether the initiator determines the receiver is or the receiver determines the initiator.
Its a tradeoff between simplicity and re-usability. Lets take an metaphor of "Sending the email" process:
If you know the recipients and they are finite in number that you can always determine, its as simple as putting them in "To" list and hitting the send button. Its simple as thats what we use most of the time. This is calling the function directly.
However, in case of mailing list, you don't know in advance that how many users are going to subscribe to your email. In that case, you create a mailing list program where the users can subscribe to and the email goes automatically to all the subscribed users. This is event modeling.
Now, even though, in both above option, emails are sent to users, you are a better judge of when to send email directly and when to use the mailing list program. Apply the same judgement, hope that you would get your answer :)
Cheers,
Ajit.
I have been working with a huge code base at my previous work place and have seen, that using events can increase the complexity quite a lot and often unnecessarily.
I had often to reverse engineer existing code in order to fix it or to extend it.
In both cases, it is a lot easier to understand what is going on, when you can simply read a list of function calls instead of just seeing the raise of an event.
The event forces you to look for usages in order to fully understand what is happening. Not a problem with modern IDEs, but if you then encounter many functions, which also raise events, it quickly becomes complex. I had encountered cases, where it mattered in what order functions did subscribe to an event, even though most languages don't even gurantee a calling order...
There are cases when it is a really good idea to use events. But before you start eventing, consider the alternative. It is probably easier to read and mantain.
A Classic example for the use of events is a UI framework, which provides elements like buttons etc.
You want the function "ButtonPressed()" of the framework to call some of your functions, so that you can react to the user action.
The alternative to an event that you can subscribe to, would for example be a public bool "buttonPressed", which the UI framework exposes
and which you can regurlary check for beeing true or false. This is of course very ineffecient, when there are hundreds of UI elements.

I Need an Analogy: Triggers and Events

For another question, I'm running into a misconception that seems to arise here at SO occasionally. Some questioners seem to think that Triggers are to Databases as Events are to OOP.
Does anyone have a good analogy to explain why this is a flawed comparison, and the consequences of misapplying it?
EDIT:
Bill K. has hit it correctly, but maybe doesn't see the importance of the critical differeence between the event and the callback function that strikes me, anyway. Triggers actually cause code to execute every time the event occurs; callbacks only occur whenever one has been registered for an event (which is not true for the vast majority of events); and even then, in most cases the callback's first action is to deregister itself (or at least the callback contains a qualifcation exit so it only executes once.)
If you write a trigger, it will unfailingly execute every time the event occurs, because there's no way to register or deregister to code segment.
Triggers are a way to interpose repeating logic synchronously into the thread of execution (i.e. synchronicity). Events are a means to defer logic until later (i.e. implement asynchronicity).
There are exceptions and mitigations in both cases, but the basic patterns of triggers and callbacks are mostly opposite in intention and implementation. Often the distinction doesn't seem to have fully sunk in. (IMHO, YMMV). :D
They're not the same thing, but they're not unrelated.
In both cases, the mechanism can be described approximately as follows:
Some block of code declares "interest" for changes in state.
Your application affects some change.
The system runs the block of code in response to the change.
Perhaps a database trigger is more like a callback function that has registered interest in a specific event.
Here's an analogy: the event is a rubber ball that you throw. The trigger is a dog that chases after a thrown ball.
If there's some other difference that you have in mind that makes it "dangerous" (note: OP has edited this choice of word out of the question) to compare triggers and events, you can describe what you mean.
Triggers are a way to interpose
repeating logic synchronously into the
thread of execution (i.e.
synchronicity). Events are a means to
defer logic until later (i.e.
implement asynchronicity).
Okay, I see what you mean more clearly. But I think it's in some ways subject to the implementation. I wouldn't assume an event handler has to deregister itself; it depends on the system you're using. A UNIX signal handler, for example, has to prevent itself from catching a new signal while it's already handling one. But a Java servlet inside a Tomcat container should be thread-safe because it may be called concurrently by multiple threads. They're both event handlers, of different kinds.
Event handlers may be synchronous or asynchronous. Can a handler in a publish/subscribe system read messages that were posted recently, but prior to the handler registering its interest? Or only messages posted concurrently?
There's another important reason to treat triggers as different from event handlers: I frequently recommend against doing anything in a trigger that affects state outside the database.
For example, sending an email, writing to a file, posting to a web service, or forking a process is inappropriate inside a trigger. If for no other reason than the transaction that spawned the trigger may be rolled back, but you can't roll back those external effects. You may not even be using explicit transactions, but say you send an email in a BEFORE trigger, but the operation fails because of a NOT NULL constraint or something.
Instead, all such work should be done by code in one's application, after one has confirmed that the SQL operation was successful and the transaction committed.
It's too bad that people keep trying to do inappropriate work inside a trigger. There are senior developers at MySQL who promote UDFs to read and write data in memcached. Wow -- I just noticed these have made it into the MySQL 6.0 product!! Shocking!
So here's another attempt at an analogy, comparing triggers and events to the process of a criminal trial:
A BEFORE trigger is an allegation.
An AFTER trigger is an indictment.
COMMIT is a conviction after a guilty verdict.
ROLLBACK is an acquittal after an innocent verdict.
You only want to put the perpetrator in prison after they are convicted.
Whereas an EVENT is the crime itself.

Resources