MVVM Light Messenger executing multiple times - mvvm-light

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">

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.

How to initialise controllers using provider state in flutter

I recently refactored half my app to use the provider pattern and i now have a problem. The main issue is that i need to initialise controllers in the init (e.g. a text controller to have an initial value or the list size of a tab controller)
How am i meant to init Controllers if the data i need has to come from the state in the build method.
For example.
// This must go in the build as it requires state
myTabsController = TabController(length: myState.list.length, vsync: this);
I'm initialisng the controller every time it builds now... How am i meant to put this in the init but still access the state variables (as there is no context).
I've tried using the afterFirstLayout() callback from the AfterLayoutMixin library but that just causes more problems. Currently with the tab bar it flashes error as no tab initialised for the first frame and then displays properly when the afterFirstLayout is called and initialises the tab. This seems like a hacky fix
I would like to learn more about how to use this pattern properly and what would be the best solution to this problem.
Feel free to ask me to clarify more.
Thanks for your help.

'ChromiumWebBrowser' does not contain a definition for 'NewScreenshot'

I'm just looking into CefSharp and am confused about NewScreenshot. I've found lots of references to it as well as example code, but none of it works. I found it marked as obsolete in the 63.0 docs...
Has NewScreenshot been removed? If so, what replaces it (how can I tell that the screen has rendered)? For my purposes a blocking (non-async) method would work fine.
Update:
Searching the source for the latest version of CefSharp I find no reference to NewScreenshot.
I started with the Minimal Example that #amaitland referred to. I made a few changes, adapting it for my use. As part of that change I moved the Shutdown() call to the program's destructor.
When I ran the project I received a mystifying error about calling Shutdown() from a thread different than the thread from which Initialize() was called.
Looking through the code I saw ScreenshotAsync and, as I wasn't (knowingly) using another thread, suspected it may be involved. I looked for another way to get my SVG image and found NewScreenshot. Which of course didn't solve my problem, which was that the GC was running my destructor in a different thread (I had no idea that could happen).
At any rate, by this time I'd shucked ScreenshotAsync for NewScreenshot which is how I ended up here.
I set a breakpoint in my handler (which I haven't included as it's never called). Here's what I hope is the relevant code. I've omitted the init code but I believe it's unchanged from the example.
public static void Main()
{
private const string url = "https://www.google.com/";
browser = new ChromiumWebBrowser();
browser.Paint += OnBrowserPaint;
browser.Load(url)
Console.ReadKey();
}
In stepping through the code in the debugger, I set a breakpoint on browser.Load(url). If I examine browser.Paint, I find errors:
Here's the tooltip for DeclaringMethod:
I have no idea if this is related to my event handler not firing, but want to point it out in the event it is involved.
I appreciate your other suggestions but feel I need to find out why an event that should be firing is not.
I'll be happy to reduce and upload the project if it will help. Oh, and thanks for your help!

AVURLAsset loadValuesAsynchronouslyForKeys, synchronous version?

is there a way to load an AVURLAsset in a synchronous manner?
My scenario is one which I need to load the assets in the background while showing a different view and change to the view showing the AVPlayer when the assets are ready to play. Not before.
I've tried loading async and calling a delegate method to tell "the assets are ready, you can show the next view", but if I get a mem warning before that, the views containing the assets in the background get released before they finish loading...so i never get the delegate call. That's why I rather do it synchronously.
Any ideas?
I'm not 100% sure I understand what you're getting at, but I believe you should be able to just use [AVURLAsset commonMetadata] or [AVURLAsset metadataForFormat:[[AVURLAsset availableMetadataFormats] lastObject]] and then show your view once this information has been loaded. Theses methods return an array of AVMetadataItems, which you should rather easily be able to traverse with a for loop. Sorry if this wasn't what you were looking for.

AIR Application enabled=false not processed (Busyindicator)

In my AIR application (with mate-Framework) i did follwing things:
click on a button
call a method in my model "onApplicationBusy"
apply some filter in arraycollections.
In my onApplicationBusy there is this code:
FlexGlobals.topLevelApplication.enabled = false;
FlexGlobals.topLevelApplication.
I trace every step and all methods are called in right order.
But my application never becomes disabled.
Why. Is there a method for this purpose.
I try InvalidateDisplayList or ValidateNow or callLater. But all tries won't work. Probably i try it on the wrong place?
I assume, my application is so busy while applying filters (4 values for 10.000 lines) that the disabled property can't processed.
If i call the method without applying the filters all works fine.
If i call just the disbaled property but never enable the app again, the app will shown as disabled after applying the filters. for me too late.
What i origin want is a clear behavior, when the app is busy and when not (ready for clicking on buttons and all this stuff).
If you can help me or know a method, how can i shown a busy application, please help me
Thanks
Frank
All right, the setTimeout Method solve my issue. I assume, I have to wait for the next screen refresh.
Why callLater won't work and when i have to implement those functions, because i have too less ressources while my filterFunction is running?
Frank
I'm using FlexGlobals.topLevelApplication.stage.mouseChildren = false | true;
Worth noting that I first tried setting the mouseEnabled flag but found various visual elements would not update at all while mouseEnabled = false.

Resources