Main

WeakEventManager To Stop Memory Leaks! (Xamarin Community Toolkit)

In the same area as AsyncCommand and AsyncValueCommand, we also have the WeakEventManager and DelegateWeakEventManager in the Xamarin Community Toolkit. Don't worry about unsubscribing your events ever again and accidentally creating memory leaks. In this episode I am joined by Brandon Minnick, Senior Cloud Advocate at Microsoft who has implemented all of the above and loves to tell you everything about it. **Show Links:** * [Xamarin Community Toolkit on GitHub](https://github.com/xamarin/XamarinCommunityToolkit?WT.mc_id=xamarin-c9-jamont) * [Documentation: Xamarin Community Toolkit](https://docs.microsoft.com/xamarin/community-toolkit?WT.mc_id=xamarin-c9-jamont) * [Documentation: WeakEventManager](https://docs.microsoft.com/xamarin/community-toolkit/helpers/weakeventmanagert?WT.mc_id=mobile-13724-bramin) * [Documentation: DelegateWeakEventManager](https://docs.microsoft.com/xamarin/community-toolkit/helpers/delegateweakeventmanager?WT.mc_id=mobile-13724-bramin) * [GitHub Sample](https://aka.ms/AsyncCommandSample) * [GitHub - AsyncAwaitBestPractices](https://github.com/brminnick/AsyncAwaitBestPractices) * Never Miss an Episode: [Follow @TheXamarinShow](https://twitter.com/thexamarinshow) **Useful Links:** * Learn more about [Xamarin](https://dotnet.microsoft.com/apps/xamarin?WT.mc_id=xamarin-c9-jamont) * Learn more about [Xamarin.Forms](https://dotnet.microsoft.com/apps/xamarin/xamarin-forms?WT.mc_id=xamarin-c9-jamont) * Learn more about [Cross-platform development](https://dotnet.microsoft.com/apps/xamarin/cross-platform?WT.mc_id=xamarin-c9-jamont) * [Xamarin Developer Center](https://aka.ms/xamarin-ch9-docs) * [Xamarin Blog](http://devblogs.microsoft.com/xamarin) * [Microsoft Learn Self-Guided Training](http://aka.ms/learn-xamarin) * [Create a Free Account (Azure)](https://aka.ms/xamarinazurefree) * [Xamarin Developers YouTube Channel](https://www.youtube.com/c/xamarindevelopers) * [Xamarin on Twitter](http://twitter.com/xamarinhq) * Get your questions answered on the Microsoft Q&A for .NET - http://aka.ms/dotnet-qa * Learn Xamarin & .NET with free self-guided learning from Microsoft Learn: http://aka.ms/learndotnet #XamarinCommunityToolkit #MVVM #Async #Xamarin

Xamarin Developers

2 years ago

>> Be sure to catch this episode of The Xamarin Show where I have Brandon on, and he will tell us all about the WeakEventManager that will prevent you from any memory leaks ever happening in your apps. [MUSIC] >> Hello, and welcome to another episode of the Xamarin Show, all about Xamarin Community Toolkit. I'm joined today by Brandon Minnick. Hey, Brandon. How are you doing? >> Hey, Gerald. Thanks for having me back. >> Of course, because you had in this previous episode a great story about the
async commands at the async, all of the things, which is really great. But together with that, hand in hand, we also have something about the WeakEventManager. What's that all about? >> That's right. Yeah, if you haven't seen the last episode we did on async command, go check it out because we're picking up where we left off. Yeah, we have this thing called WeakEventManager in the Xamarin Community Toolkit. It will basically help save you from memory leaks. I don't know about you, Gerald, but m
y most common memory leak in all my apps is always just I forget to unsubscribe my EventHandlers. I'll subscribe to an event and then I forget to unsubscribe it. Sometimes that's okay because sometimes the garbage collector will still figure out that we're done and we can move on, we can free up that chunk in memory. There's times where maybe there's a static reference in that event, or maybe you're referring to another class that hasn't been yet garbage collected, what we have is the WeakEventM
anager that essentially solves that for you. Makes it so like you don't have to unsubscribe, and the garbage collector can still clean up the class that contains this event. Hopefully, there will be no more memory leaks because of Event Managers. Thanks to the WeakEventManager. >> That's what I love, just add that little bit of magic. I don't need to understand everything that's underneath it and my memory leaks will just go away. That's the way I love it. Now, of course, you have to understand
what's happening underneath because that's important to know what's going on in your application. But the less stuff that we actually need to think about with this, the better. With these WeakEventManagers, I think you're going to have a little bit of code for us to look at. But how are we going to use that in our application? >> Let's jump back into the code here. In this view model, we have an event called GetLatestReleaseFailed. To fill you in, this is just an app that will ping the GitHub AP
Is and tell us the latest version of Xamarin Community Toolkit. We tap the button, we find out we're on version 1.0.2. That worked so great. But had it failed, we do propagate that as an event up to our view. Our content page will handle that. We subscribe to it, we'll handle it here, and really all we're doing is just displaying an alert to the user to let them know something went wrong. I like to do that here in the view to keep all my UI stuff in one place. That's why we're propagating up to
this event. That's great. But like we talked about a minute ago, if we forget to unsubscribe this EventHandler, it's not guaranteed that you'll have a memory leak, but it leaves the door open, it opens the possibility for a memory leak. Let's check out the WeakEventManager to see how we can just solve that hopefully forever. What we can do is we can create a WeakEventManager, I'm going to say type string because this is an EventHandler of type string. Let's just call it getlatestReleasesFailedEv
entManager has some verbose. But what I say is, I'm still using some C-sharp. I can just say New, and it just works. I love that. We want to just initialize this right away. Keep it read-only because you'll never have to re-initialize it or change it, and then what we do is we come down to the event, and this might look a little weird because before I started using WeakEventManagers, I didn't know you could do this. You can actually set what happens when you add or remove or subscribe and unsubs
cribe to an event, and so instead of letting the default, subscription in dot Net to the event happened, we're actually going to take it and say instead, add that subscription to our WeakEventManager, and likewise, when somebody says, Unsubscribe, we're going to say remove it from our WeakEventManager, and so now anytime anybody's subscribes to this event, we actually going through this WeakEventManager, and you can check out the code. It's all open-source in the toolkit. But what's happening un
der the hood is that WeakEventManager is actually using reflection to do the subscriptions, and that's the magic for how we avoid the memory leaks because there's no hard coupling, there is no dependency. When the garbage collector comes through to say, dispose of this view model or dispose of our view, it'll look and see, is this still connected to anything like is this referencing any other classes, any other code, anything that would prevent me from garbage collecting this? When it looks at t
his WeakEventManager it will say, "No there's no hard connections. I can get rid of it." Even though you and me Gerald we know that we never unsubscribe from this event. That's the secret sauce underneath the hood, and this is all we have to do, just a couple of lines of code, and we can avoid any future memory leaks caused by forgetting the unsubscribed from this event. >> That is so cool. Actually, I did know also about the Add and Remove, but that was because I was working on Xamarin forms an
d I think we've used this. Let me ask you this thing because everyone has the INotifyPropertyChanged in Xamarin forms. Because that's what we're using with, we're good citizens we are trying to do MVVM, and INotifyPropertyChanged is a big thing there, and that also has the event of property changing a couple of events. I tried to use this toolkit the WeakEventManager for that, but that didn't really work. What's what's going on there? >> Great question. If we jump down to I've got the BaseViewMo
del here with INotifyPropertyChanged. There's a couple of things going on here, so let's just instantiate WeakEventManager. We'll call it PropertyChangedEventManager, and what's actually interesting about this is the Xamarin forms Weak Event Manager. Xamarin forms actually exposes a WeakEventManager class themselves. It's the toolkit that actually gives us the type T. If I change that to string, then we'll see that namespace wanted to bring in our toolkit. Xamarin forms, it has a WeakEventManage
r. We can add that in here, and let's see what happens. Remove. There we go, and yeah, like you are alluding to a minute ago, we're getting a bunch of red squiggles. What's happening here? Well, the Xamarin forms WeakEventManager is actually will say hard-coded to only use EventHandlers, and so we can use it for anything that has this EventHandler. Public Event, EventHandler, great. Xamarin forms want to work just fine. But what we did in the toolkit, we expanded it because EventHandlers are onl
y one type of event. You can have events that are of type action. You can have events that are type delegate, and that's actually a problem we're running into here with Property Changed. This Property Changed EventHandler is of a type delegate. What we did in the toolkit, we created, and make sure I spell that right de-le-gate there it is. That's Intellisense. There you go. We have the DelegateWeakEventManager, and so it's similar to the one that Xamarin forms provides out of the box, and to be
honest, when I created the DelegateWeakEventManager was actually inspired by the Xamarin forms WeakEventManager, but it's expanded so we can use it for delegate events like this, and I did forget to mention something earlier, and I'm seeing it glaringly right now with these red squiggles. When we add WeakEventManagers, we're going to get this red squiggle. We just tried to say, say Property Changed dot Invoke or event name dot Invoke, and all we have to do instead is say, we have to just referen
ce our Event Manager and we'll just tell it to raise the event, and then the syntax is a little different. We still pass in the center, we still pass in the eventArgs. This is still valid. New property changed eventArgs is still valid. The only thing we also need to add is the name of the event. Getting back to what we were chatting about a minute ago, because Weak Event Managers use reflection to fire these events and keep track of what's subscribed to which event. By passing in the name of the
event, just using the name of property. That's what allows the PropertyChangedEventManager to fire, shame on me, I forgot to add that up here. In our first view model. >> That's good because now. >> We didn't get the right [inaudible] . >> Exactly. It's going to help us anyway. It's good to remind us, don't worry about that, and this is good. Because this is the scenario that people will come across as well. They'll notice red squiggles and now they know how to solve it and why this is happenin
g. All good. >> Yeah. Turns out even if you created the library, then you'll still feel something sometimes. >> Oh yes, absolutely. This is awesome stuff Brandon. I'm sure that we will see apps without memory leaks now, so that is going to be really great. There is a lot of other cool stuff going on and examined communities but this is definitely a little bit more of the hardcore stuff, I'll be honest. But that's what Brandon is all about, and I think you will have to have a play with it yoursel
f to see what it's all about. Of course, this project is open source. You can find it on the link down here below. Also in the video description for you to click on and you'll find a couple of other links there as well. Thank you so much Brandon for coming on the show and explaining everything there is to know about this WeakEventManager and showing us how to use it. Thank you everyone for watching joining the show. There will be next episodes, of course, with all the things in the Xamarin Commu
nity Toolkit. If you want to be notified automatically, be sure to click that "Subscribe" button. Click that "Like" if you've like this video and I'll be seeing you for the next one. [MUSIC]

Comments

@mehmetavsar

We all need more Brandon positivity in our lives.

@andresolivares

nice find Brandon. I too have seen this a while back in my WPF, Silverlight days but never dug in. I'm gonna revisit some of my Xamarin stuff now. Thx so much.

@blinkskaterkc

Brandon is the man

@henda79

Great work guys as always, this is something what could help many developers. I know for sure I forget to unsubscribe events :/

@DamianWalczak

Im a fan of Brandon I wish I was half as happy as he is :D

@johnb2572

Awesome work guys, thank you for making our lives better :)

@robertojrcantos1711

This is awesome!!! I will add it to my project. Thank you for the help.

@LeonardHarrisLH

Love these videos 😍

@TimoPijnappel

Thanks, great video! I am wondering about the best practices here. Would I create a WeakEventManager for every single event (.. about to create a snippet here...)? Or would it be better to create a WeakEventManager for every method signature in my class. Say I have multiple EventHandler<string> events. Should they share a WeakEventManager or should I create a new one for every event?

@bomite

Thaks for this great improvement. Now my app is running in any Android device(5 > X). Is fantastic only this class saving memory

@marthinch

wow, it's so simple to handle memory leak, i'll try it soon.

@Shnaz88

I am experiencing some issues with anonymous methods not getting called when subscribing to an event managed by the Weakeventmanager, anyone with same problem?

@SalehWolf

Hello How To use Toolkit animation in mvvm? i dont understand source code of github

@_samirdahal

Thanks for the video Gerald and Brandon. So just one WeakEventManager can be used to subscribe and raise to different events in a view model? Brandon used one WeakEventManager to raise the PropertyChangedEvent. If I have multiple events can I used the same manager to do the same?

@maksym.koshovyi

Also XCT has ObservableObject class that implements INotifyPropertyChanged using WeekEventManager, so you don't need to implement it yourself

@emilalipiev7472

are those both Surface earphones? white one is obviously but black one?

@overzealus

What about performance? Reflection should give a big performance impact :(