Is it equivalent/better to work
with the Event module on Event type
or with Observable on the publish property of an event
Functionally it seems equivalent, and I guess the difference is 'semantic' :
Are we inside the boundary where it makes sense to have access to the internal state of
the event ?
Or are we considering this event interface as a passive source from which a stream was exposed to us
Is that the correct thinking ?
The main difference between Event and Observable is in how they handle state and un-subscription.
Event functions attach to the source event and do not give you any way to unsubscribe. If you use stateful combinators (like Event.scan) and then attach multiple observers to the resulting event, then they will all see the same state.
Observable functions construct "specification" of the processing pipeline. When you attach a handler to IObservable value, you get back an IDisposable that can be used to remove all handlers. Each handler attached to IObservable will get a new state (because the runtime creates a new processing chain according to the "specification").
In practice, the main difference is in the statfullness - if you want to share state, you can use the Event module - implementing the same using Observable is possible but harder.
If you're using events inside async, then you should use Observable and AwaitObservable (instead of built-in AwaitEvent), because using event combinators will leak memory - it will attach event handlers that are never removed.
Related
I want to implement a Axon projection providing a subscription query. The projection persists entities of a specific based on the events (CRUD). The following should happen if a replay of the projection is executed:
Inform about a empty collection via the subscription query.
Process the events until the projection catches up with the event store.
Inform about the current state of the entities via the subscription query.
My intention is that the subscription query should not inform about many events in a very short time and I want to prevent informing about many intermediate positions (e.g. create and delete a specific entity, it should not be used in the subscription query, because it is not available after catching up).
Currently I cannot implement the third step, because I miss a hook for reacting to the moment when the Axon projection is catching up again.
I use Axon v4.5 and Spring Boot v2.4.5.
At the moment, the Reference Guide is sadly not extremely specific on how to achieve this. I can assure you though that work is underway to improve the entire Event Processor section, including a clearer explanation of the Replay process and the hooks you have.
However, the possible hooks are stated as it is (you can find them here).
What you can do to know whether your event handlers are replaying yes/no, is to utilize the ReplayStatus enumeration. This enum can be used as an additional parameter to your #EventHandler annotated method, holding just two states:
REPLAY
REGULAR
This enumeration allows for conditional logic within an event handler on what to do during replays. If an event handler for example not only updates a projection but also sends an email, you'd want to make sure the email isn't sent again when replaying.
To further clarify how to use this, consider the following snippet:
#EventHandler
public void on(SomeEvent event, ReplayStatus replayStatus) {
if (replayStatus == REGULAR) {
// perform tasks that only may happen when the processor is not replaying
}
// perform tasks that can happen during regular processing and replaying
}
It's within the if-block where you could invoke the QueryUpdateEmitter, to only emit updates when the event handler is performing the regular event handling process.
I'm working in the Symfony2 framework and wondering when would one use a Doctrine subscriber versus a listener. Doctrine's documentation for listeners is very clear, however subscribers are rather glossed over. Symfony's cookbook entry is similar.
From my point of view, there is only one major difference:
The Listener is signed up specifying the events on which it listens.
The Subscriber has a method telling the dispatcher what events it is listening to
This might not seem like a big difference, but if you think about it, there are some cases when you want to use one over the other:
You can assign one listener to many dispatchers with different events, as they are set at registration time. You only need to make sure every method is in place in the listener
You can change the events a subscriber is registered for at runtime and even after registering the subscriber by changing the return value of getSubscribedEvents (Think about a time where you listen to a very noisy event and you only want to execute something one time)
There might be other differences I'm not aware of though!
Don't know whether it is done accidentally or intentionally.. But subscribers have higher priority that listeners - https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php#L73-L98
From doctrine side, it doesn't care what it is (listener or subscriber), eventually both are registered as listeners - https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/EventManager.php#L137-L140
This is what I spotted.
You should use event subscriber when you want to deal with multiple events in one class, for example in this symfony2 doc page article, one may notice that event listener can only manage one event, but lets say you want to deal with several events for one entity, prePersist, preUpdate, postPersist etc... if you use event listener you would have to code several event listener, one for each event, but if you go with event subscriber you just have to code one class the event susbcriber, look that with the event subscriber you can manage more than one event in one class, well thats the way i use it, i preffer to code focused in what the model business need, one example of this may be went you want to handle several lifecycle events globaly only for a group of your entities, to do that you can code a parent class and defined those global methods in it, then make your entities inherit that class and later in your event susbcriber you subscribe every event you want, prePersist, preUpdate, postPersist etc... and then ask for that parent class and execute those global methods.
Another important thing: Doctrine EventSubscribers do not allow you to set a priority.
Read more on this issue here
Both allow you to execute something on a particular event pre / post persist etc.
However listeners only allow you to execute behaviours encapsulated within your Entity. So an example might be updating a "date_edited" timestamp.
If you need to move outside the context of your Entity, then you'll need a subscriber. A good example might be for calling an external API, or if you need to use / inspect data not directly related to your Entity.
Here is what the doc is saying about that in 4.1.
As this is globally applied to events, I suppose it's also valid for Doctrine (not 100% sure).
Listeners or Subscribers
Listeners and subscribers can be used in the same application indistinctly. The decision to use either of them is usually a matter
of personal taste. However, there are some minor advantages for each
of them:
Subscribers are easier to reuse because the knowledge of the events is kept in the class rather than in the service definition.
This is
the reason why Symfony uses subscribers internally;
Listeners are more flexible because bundles can enable or disable each of them conditionally depending on some configuration value.
http://symfony.com/doc/master/event_dispatcher.html#listeners-or-subscribers
From the documentation :
The most common way to listen to an event is to register an event
listener with the dispatcher. This listener can listen to one or more
events and is notified each time those events are dispatched.
Another way to listen to events is via an event subscriber. An event
subscriber is a PHP class that's able to tell the dispatcher exactly
which events it should subscribe to. It implements the
EventSubscriberInterface interface, which requires a single static
method called getSubscribedEvents().
See the example here :
https://symfony.com/doc/3.3/components/event_dispatcher.html
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.
Is there any pattern by which a consumer of an INotifyPropertyChanged can avoid memory leaks even in circumstances where an arbitrary number of instances of the consumer may be created during the lifetime of a particular INotifyPropertyChanged object, without any of that object's properties being changed (and thus notifications firing)? It's possible for an event publisher to implement weak events with some Reflection trickery; is there any workable subscriber-side weak event pattern?
If the Event contract required that an event publisher must allow event subscribers to unsubscribe at any time, from any thread, without blocking indefinitely, then it would be possible for an event subscriber to have objects that were actually "interested" in the subscriber keep a reference to a wrapper object, and have the wrapper object override Finalize() to tell the subscriber object to unsubscribe. Unfortunately, even if subscriber discovers via Finalize() that it should cancel its subscription, the .net Event contract does not require that objects which publish events must allow them to be safely disposed from within a finalizer. Indeed, the default event implementation for C# is in fact not safe to call from within a finalizer (the current implementation acquires a lock on the object publishing the subscription; if the lock were only used for subscription and unsubscription that wouldn't be a problem, but there's no guarantee that the lock won't be held for some other purpose for some arbitrary length of time). Earlier implementations were worse: if a class attempted to subscribe or unsubscribe to its own events, subscription and unsubscription wouldn't be thread-safe at all.
If one knew that the INotifyPropertyChanged object was some particular class which implemented its events in thread-safe manner (for subscription, acquire a lock and then use an Interlocked.Exchange spin-loop; for unsubscription, use a spin-loop which will acquire the lock if available but will try the Interlocked.CompareExchange whether the lock is available or not) one could safely remove the event handler in a finalizer. If one knew that the object would be raising the event with some significant frequency, one could perhaps remove the handler from within the event (though I'm not sure the .net event contract requires that to be safe either). Is there any general-purpose solution which will work no matter what type of INotifyPropertyChanged implementer one is given to watch?
EDIT--Clarification
The idea isn't that an object would unsubscribe from its own finalizer, but rather that objects which were interested in the effects of the event would hold references to a wrapper object, to which the event-handling itself would not hold a reference. For example, suppose the goal was to count how many times a PropertyChanged event was raised with a particular event-name string. One could have a PropertyChangeCounter object, which held a reference to a PropertyChangeCounter.Internals object; the latter object would hold the event subscription and the change count. The ChangeCount property of the PropertyChangeCounter object would return the value of the nested PropertyChangeCounter.Internals ChangeCount. The wrapper object would become eligible for finalization once no outsider held a reference to it, and its finalizer could call an unsubscribe method in the PropertyChangeCounter.Internals object.
I have an object that is updated from a polling loop on a thread. This object fires particular events when data changes, etc.
I'm trying to use this object in conjunction with a windows form, where I create event handlers on the form to update the UI. Of course, this causes cross-thread operation exceptions if I try to manipulate the UI directly in these handlers.
I can get it to work by going through the standard procedure of checking InvokeRequired, using a delegate, blah blah blah. But I want to publish this object as a library, and I don't want end-users to have to worry about all that.
I want my object to somehow take care of synchronizing those event callbacks with the form so that end-users can manipulate the UI elements in those handlers worry-free.
Is there a way to do this??
If your object is always related to a single form, there is a simple trick indeed. The important fact here is, that you instanciate your object from the thread you like to affect the form later.
The trick is to instanciate a simple Control (new Control()) in your object in the constructor. When you perform logic on your form, use the Invoke/BeginInvoke methods on this simple control, to dispatch the action to the correct calling thread. So you have the dispatching logic directly in your object and there is no need for other users of your object to take care about this.