mvvm-light RaisePropertyChanged messenger not broadcasted - mvvm-light

I cant seem to get this working properly.
I've got two ViewModels. VM1 registers a message with the following code
Messenger.Default.Register<PropertyChangedMessage<int>>(
this,
(action) => DispatcherHelper.CheckBeginInvokeOnUI(() => UpdateOverlayIcon(action.NewValue))
);
VM2 fires the RaisePropertyChanged when property is being set.
// Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
RaisePropertyChanged(UnreadTweetsPropertyName, oldValue, value, true);
Now, shouldn't the VM1.UpdateOverlayIcon() method run right after the RaisePropertyChanged is fired in VM2? Or have i missed an essential part of this, because it doesn't work for me? I have been struggling with this all day long and tried a number of different methods.

This should work quite easily - just make sure that the Message Register code is being registered before the RaisePropertyChanged notification is called.
The other thing to check is that your types match - so you are listening for a Message with INT - is this the type of UnreadTweetsPropertyName? (it wont receive it if they dont match).
The problem with this approach is that ANY int property that is broadcasting will be received... I would like to be able to pass in a token so that I can match them up...

Related

How to make command to wait until all events triggered against it are completed successfully

I have came across a requirement where i want axon to wait untill all events in the eventbus fired against a particular Command finishes their execution. I will the brief the scenario:
I have a RestController which fires below command to create an application entity:
#RestController
class myController{
#PostMapping("/create")
#ResponseBody
public String create(
org.axonframework.commandhandling.gateway.CommandGateway.sendAndWait(new CreateApplicationCommand());
System.out.println(“in myController:: after sending CreateApplicationCommand”);
}
}
This command is being handled in the Aggregate, The Aggregate class is annotated with org.axonframework.spring.stereotype.Aggregate:
#Aggregate
class MyAggregate{
#CommandHandler //org.axonframework.commandhandling.CommandHandler
private MyAggregate(CreateApplicationCommand command) {
org.axonframework.modelling.command.AggregateLifecycle.apply(new AppCreatedEvent());
System.out.println(“in MyAggregate:: after firing AppCreatedEvent”);
}
#EventSourcingHandler //org.axonframework.eventsourcing.EventSourcingHandler
private void on(AppCreatedEvent appCreatedEvent) {
// Updates the state of the aggregate
this.id = appCreatedEvent.getId();
this.name = appCreatedEvent.getName();
System.out.println(“in MyAggregate:: after updating state”);
}
}
The AppCreatedEvent is handled at 2 places:
In the Aggregate itself, as we can see above.
In the projection class as below:
#EventHandler //org.axonframework.eventhandling.EventHandler
void on(AppCreatedEvent appCreatedEvent){
// persists into database
System.out.println(“in Projection:: after saving into database”);
}
The problem here is after catching the event at first place(i.e., inside aggregate) the call gets returned to myController.
i.e. The output here is:
in MyAggregate:: after firing AppCreatedEvent
in MyAggregate:: after updating state
in myController:: after sending CreateApplicationCommand
in Projection:: after saving into database
The output which i want is:
in MyAggregate:: after firing AppCreatedEvent
in MyAggregate:: after updating state
in Projection:: after saving into database
in myController:: after sending CreateApplicationCommand
In simple words, i want axon to wait untill all events triggered against a particular command are executed completely and then return to the class which triggered the command.
After searching on the forum i got to know that all sendAndWait does is wait until the handling of the command and publication of the events is finalized, and then i tired with Reactor Extension as well using below but got same results: org.axonframework.extensions.reactor.commandhandling.gateway.ReactorCommandGateway.send(new CreateApplicationCommand()).block();
Can someone please help me out.
Thanks in advance.
What would be best in your situation, #rohit, is to embrace the fact you are using an eventually consistent solution here. Thus, Command Handling is entirely separate from Event Handling, making the Query Models you create eventually consistent with the Command Model (your aggregates). Therefore, you wouldn't necessarily wait for the events exactly but react when the Query Model is present.
Embracing this comes down to building your application such that "yeah, I know my response might not be up to date now, but it might be somewhere in the near future." It is thus recommended to subscribe to the result you are interested in after or before the fact you have dispatched a command.
For example, you could see this as using WebSockets with the STOMP protocol, or you could tap into Project Reactor and use the Flux result type to receive the results as they go.
From your description, I assume you or your business have decided that the UI component should react in the (old-fashioned) synchronous way. There's nothing wrong with that, but it will bite your *ss when it comes to using something inherently eventually consistent like CQRS. You can, however, spoof the fact you are synchronous in your front-end, if you will.
To achieve this, I would recommend using Axon's Subscription Query to subscribe to the query model you know will be updated by the command you will send.
In pseudo-code, that would look a little bit like this:
public Result mySynchronousCall(String identifier) {
// Subscribe to the updates to come
SubscriptionQueryResult<Result> result = QueryGateway.subscriptionQuery(...);
// Issue command to update
CommandGateway.send(...);
// Wait on the Flux for the first result, and then close it
return result.updates()
.next()
.map(...)
.timeout(...)
.doFinally(it -> result.close());
}
You could see this being done in this sample WebFluxRest class, by the way.
Note that you are essentially closing the door to the front-end to tap into the asynchronous goodness by doing this. It'll work and allow you to wait for the result to be there as soon as it is there, but you'll lose some flexibility.

symfony 5 - disable subscriber

I am using bugsnag in a symfony 5 project to keep track of exeptions. I also use symfony messenger with rabbit for heavy processing.
Everything works fine overall, except the fact that in some cases, inside a messenger middleware (RejectRedeliveredMessageMiddleware) an exception is thrown in some particular cases in order to trigger a message reque while avoiding a possible infinite loop (RejectRedeliveredMessageException).
The exception should be there, and the behavior is correct. For example if a process stopped unexpectedly (a hard reboot or a kill), the message is requed. The logic works well, autorecovery works perfectly.
The only problem is that bugsnag registers itself as a subscriber for all kernel events, treated or not (code below)
$listeners = [
KernelEvents::REQUEST => ['onKernelRequest', 256],
KernelEvents::EXCEPTION => ['onKernelException', 128],
];
Normally exceptions are caught in our app before getting to the general event dispatcher and so they are not reported if they shouldn't. But, because that is in the middleware, and an event is risen it gets reported even though is already treated by the autoretry mechanism and because of that it generates a lot of noise and fake positives.
What I would need to do is unsubscribe for a particular event, but since I can't touch the 3rd party code (bugsnag and messenger) I can't find a way to do it.
Is there a way to programatically remove an event from a subscriber?
Inject EventDispatcherInterface and use removeSubscriber() method. You can do this in you custom middleware https://symfony.com/doc/current/messenger.html#middleware
It's hard to tell if this would work, but it's an angle - when you detect your Event is handled properly, you could invoke $event->stopPropagation(), perhaps from your own listener, which should: "... tell the dispatcher to stop all propagation of the event to future listeners (i.e. to not notify any more listeners)"
https://symfony.com/doc/current/components/event_dispatcher.html#stopping-event-flow-propagation

return type for event in TinyOS

I'm implementing a module using nesC for TinyOS. My modules uses interface Timer<> so I have to implement the event fired of the interface Timer, it is possible to return a value inside this implementation or an event must be always void?
The return type of the Timer.fired event is defined as void and this cannot be changed. Even if the type was non-void, the returned value would be delivered to the component that signals the event, which is some system component implementing the Timer interface.
In order to get some hints on how to solve your problem, please provide more details explaining for what purpose you want to return a value from the fired event, that is, who is expected to get and process the returned value.

MVVM Light Messenger executing multiple times

I am using MVVM Light and am using Messages to communicate between ViewModels to let a ViewModel know when it is ok to execute something. My problem is that I register for a message and then it receives it multiple times. so to keep from my program executing something more than once I have to create boolean flags to see if it has already been recieved. Any idea why it does this and how I can stop it?
Make sure you unregister your message handlers once you do not need them anymore. The Messenger keeps a reference to the registered methods and this prevents them from being garbage collected.
Therefore, for ViewModels: make sure that you call Cleanup once you done (or implement IDisposable and call Cleanup from there).
For Views (Controls, Windows, or similar) call Messenger.Unregister in an event that occurs on the teardown of the view, e.g. the Unloaded event.
This is a known behaviour of the MVVM and has been discussed in several places.
Very old question but I solved the problem by doing this:
static bool isRegistered = false;
and then, in the constructor:
if( !isRegistered )
{
Messenger.Default.Register<MyMessage>(this, OnMessageReceived);
isRegisterd = true;
}
I have seen this issue before. It had to do with the Messenger.Default.Register being called more than once. The MVVMLight Messenger class will register the same item 'x' number of times. This is why when you call the Send you get it many times.
Anyone know how to prevent MVVMLight from registering multiple times?
really old but thought I would answer just in case somebody needs it. I was fairly new to silverlight at the time and the issue ended up being a memory leak as the viewModel, which had multiple instances, was still in memory.
As other contributors mentioned, the same message is being registered multiple times. I have noticed this behavior taking place while navigating to View X then navigating back to View Z where the message is registered in the constructor of the Z ViewModel. One solution is to set the NavigationCacheMode property to Required
<Page
........
........
NavigationCacheMode="Required">

PopUpWindow and null object reference

I've been struggling with this problem for last few hours but still got no idea what's wrong. Here's the scenario:
Application built on top of the Mate framework sometimes need to exchange data with remote server over plain binary socket.
When specific packet is received I have to switch view (using ViewStack) and create custom panel (using PopUpManager class). This custom panel contains a dataGrid component which has to be populated with some XML received along with mentioned packet.
Trouble is that when I try to assign XML to DataGrid's dataProvider I constantly get "Cannot access a property or method of a null object reference" error. The only thing I can think of is some kind of race when processing events and creating components.
Here are the most interesting pieces of code:
<!-- LoginEvent.LOGIN_OK _____________________________________________________________________ -->
<EventHandlers type="{LoginEvent.LOGIN_OK}">
<MethodInvoker generator="{UserManager}" method="storeCurrentUser" arguments="{event.fullName}"/>
<EventAnnouncer generator="{NavigationEvent}" type="{NavigationEvent.MAIN}"/>
<MethodInvoker generator="{CustomSocket}" method="listBoards"/>
In the above code I react when the LOGIN_OK packet is received.
Store user's data, change the view and ask the Socket class wrapper to send request (the reponse for that request is our verySpecificPacket)
Here's detailed info about how I change the view and create custom pop up. In MainUI.mxml:
<mate:Listener type="{NavigationEvent.MAIN}" method="handleNavigationEvent" />
private function launchBoardListWindow():void {
Logger.info("launchBoardListWindow()");
var win:BoardList = PopUpManager.createPopUp(this, BoardList, true) as BoardList;
PopUpManager.centerPopUp(win);
}
private function handleNavigationEvent(event:NavigationEvent):void {
viewStack.selectedIndex = MAIN;
launchBoardListWindow();
}
The third position in EventMap isn't important, it just ask socket wrapper to send some kind of packet. The server is supposed to respond with verySpecialPacket along with XML payload. And here we are at the part where the error is. In mxml describing my custom panel I set up a listener for an event which is being dispatched after my verySpecialPacket is received.
public function handleListBoardsEvent(e:ListBoardsEvent):void {
Logger.info("handleListBoardsEvent");
xmlData = e.xml;
boardList.dataProvider = xmlData.children(); // Here's the error!!!
}
I really don't get it, since the xmlData is OK, and custom panel with all child components were created. Thanks for reading!
You're likely on the right track in respect of a race condition.
Suggestion:
Put a try { ... } catch (e:Error) { trace("error"); } block around the code in your handleListBoardsEvent() method.
Then, put a breakpoint on the trace() and, when it hits, take a good look around at the various objects involved.
My guess is that you're attempting to access the boardList object before it is created - i.e. it's null.
The other possibility is that boardList.dataProvider is a setter and there's code in the setter that's barfing. (Although, if that were the case, I'm sure you would have noticed the stacktrace inFlexBuilder)

Resources