 Hi welcome to Visual Studio Toolbox. I'm your host Robert Green and joining me is Phil Jepixi. Hey Phil. Hey Robert. How are you? Great. We are continuing in our series of design patterns, and we've moved into the Studio B Just a little behind the scenes. We're taping this over the course of two days. Two days. Yesterday We did five of what's we think is going to be wind up being ten episodes. Yes And then we are here for the second day in the smaller studio different shirts different shirts different environment More comfortable chairs These are more comfortable But I think in the in the order of things one of the episodes that we taped yesterday is going to wind up being after this one Yes, so there will be some back and forth. Well, that's a TARDIS time effect that we have. Yeah, exactly Today we're talking about the observer pattern. We are. And we will also talk a little bit about Publish, subscribe. Yeah, I mean they're a long time. They're similar. Well, they're used interchangeably a lot academically They are different. Mm-hmm. So we're gonna talk about that. Okay. The code samples are all about the observer, right? Most people don't write their own pub sub. They're using something like in service bus or yeah Or something along those notification hubs or something, right? You don't you don't have to write your own pub sub plumbing, right? So let's jump into the definition again, we're leveraging Wikipedia for this So the observer pattern Has an object typically called the subject Maintains a list of observers and notifies them when any state changes using by usually by calling a method called notifier update The biggest problem with the observer pattern is memory leaks So in dot net I'm gonna have to have a strong reference to each of those observers Mm-hmm if that observer gets set to know outside of the subject The subject will not let it go. So even though you can't access it in your own code outside of the subject Mm-hmm. It's still in the list. It will never be garbage collected. Is there is that? Is that happen a lot? Do we have to worry about that or is it just a edge case you need to bear in mind? Well, so it does happen. There's a lot of documentation out there about Events and delegates and how they hold strong references But fortunately, I'm gonna show you a solution in dot net using a weak reference class. Okay, that gets past the problem. Okay All right, so let's look at the code Again, we're driving Most of this through unit testing. So if you haven't seen our episode on unit testing They kicked this whole series off go and hit pause. We'll wait Okay, this is us waiting back So we have a Subject that's a sports aggregator. I know you're a big baseball fan. So I wanted to come up with an understatement Come up with a baseball reference. So the subject is just going out there and gathering information wherever it could Wherever it can about different sporting events. Okay, and then it will Take the list of observers in this case. I've got a newspaper and a radio station and They subscribe to the service. Okay, so we register that or register them as an observer Results with the Reds beating the Cubs and oh man, because we're in here Not this year. That's true. We're doing but we we are having some struggles with starting pitching We added game result to the subject. So however that happens. That's not really part of the pattern It's just a subject gets a new game result. Somehow that's going to trigger the notify And what we want to do is make sure in our tests that we still have the observers in They've gotten notified. They've received the game score. So we make sure that they have the game results in their list And then we unregister the observers we have to specifically say I'm not paying for the service anymore Okay, and that's the only way we can free them up And then we just check to make sure that the observers are zero So let's look at how we Code this we have a very simple interface because we always want to program to an interface And it's just I subject for lack of a more creative name And then we're gonna do an entire episode on that subject On interfaces. Yeah, we can Why you say that you should always program to an interface. Yes. What does it look like when you don't and then What does it look like if you do and what does it gain you? Just that's just uh I'm just an aside. Okay, but let's do an episode on that. We will because you keep saying that I do I do keep saying it Okay All right, so I can register an observer. I can unregister an observer and I can notify the observers pretty simple, right? So here I have my sports aggregator Which implements I subject has a list of observers When the game result gets added to Irrigator now, I'm not holding on to them because again, this is just demo code Mm-hmm. I just call notify and notify simply goes through Each observer one at a time and calls the update method. Okay Now the observers also have an interface One method that we really care about which is the updates and then the list of results So the newspaper gets updated it adds this game box score to the results Okay, now the newspaper can choose what to do with it, right? It's not part of the pattern That the subject sorry that the observer does anything The pattern is that it gets notified, right? So for example a radio station can break in And say hey breaking news reds beat the cubs newspaper might have to wait till they actually print the next Paper right gonna say episode but paper or they could put it on their website, right? So it's up to them when they act on it But the pattern is we need to notify them notify one or two Now I said there is a problem with memory leaks and let me show you in this test Properly named doesn't handle no objects correctly. We set it up the same way Got our sports aggregator got the newspaper patient we register those observers We then set the first observer, which is the newspaper to know we force garbage collection But then we go through and We realize on this line right here That we still have an observer in The collection, okay, I can't unregister the observer this line won't work Because it's no because it's no right, so I can't force an unregister The observer sorry the subject doesn't know that it's been nullified because it's still holding a strong reference So this item will live on has the subject lives on Okay, no Time when we're coding things using delegates or events or even I notify property change Which is a good example of the observer pattern. Mm-hmm when that window goes out of scope and gets closed Or where the subject gets garbage collected then it'll free up all those resources Okay, so you asked how much of a problem it is it really depends on how you code your subject if the subject is the core of your program and Is around for the lifetime of your application. Mm-hmm. It's a big problem If it's just one window in a WPF application, for example, it's probably not such a big problem. Okay, right? Now I did say that there's a fix for this and That's using the weak reference class within dot net So this is something I discovered fairly recently and I think it's really cool Although it's got very specific uses What a weak reference does instead of saying hey, I want to hold on to a reference of this particular object I hold a weak reference. Mm-hmm and That allows garbage collection But it does change how we code the sports aggregator You notice it's a list of weak references of I custom observer We're registering weak references as opposed to I custom observers Mm-hmm, and when we notify we have to change things a little bit We have to instead of just saying call notify because we're Holding on to a list of weak references. We need to get to the target of that weak reference. Okay So we call try get target and this is a new feature in C sharp 6 where we don't have to declare the variable before we Make it an out parameter If it's null we go ahead and unregister it so we set it to null in our calling code and We get a notification it goes through and says hey, I'm going to let this thing go okay because it doesn't exist anymore Otherwise, I just call update normally When we look at the test for this one It's exact same test But we can unregister the weak reference even though We have set No, let me change this because I screwed up Little live coding here, so we will sorry. We're looking at the wrong test. Okay, that's the problem being live All right This is the same code. Mm-hmm. I Register a weak reference or get a weak reference back. I Set the observer to null Mm-hmm Call garbage collection but now I can Unregister if I wanted to Because it's the weak reference. It's not the actual object, but I don't need to do that Because the subject itself says hey the target of this weak reference doesn't exist anymore I'm gonna let go of the weak reference The cut the observer has already been garbage collected. Mm-hmm memory leak solved. Okay, cool. So that's Something to keep in mind as a tool if needed Yeah, and like I said, I think it's it's pretty specific where you would need it if you're doing an observer pattern and Your subject again is a long-lived item. Mm-hmm, then you need to consider this. Okay, so let's let's talk a little bit about This versus the pub sub pattern because That in the code We're we're waiting to be told that that a game Has result has occurred right right so and you mentioned that I notify Property changed is a classic example of the observer pattern. Yes, so there's a difference between needing to know or Needing an expectation that you do something versus a pub sub model where I'm Publishing you've subscribed, but you may or may not do something. Well, maybe we should talk about the definition of the pub sub. Okay So the pub sub is a again a messaging pattern, but the publishers do not send directly to the receivers Mm-hmm. There's some sort of intermediary and that can have filtering that can have routing those types of things But the publisher has no idea if it even has any subscribers it's just broadcasting right and Hopefully somebody picks it up. If not, so be it, right? So if we look at the just a comparic and trust Between the two what happened we lost the screen So we're recording blank right now. Did this come out? I don't know Hold on. There it is. Oh, now that I've unplugged it and plugged it back in There we go, okay, so we want in the studio, so we will probably cut some of that We will cut that part. Okay. All right, so we want to compare and contrast very simply. Mm-hmm, right? So the observer Pattern everybody knows each other Right. I know you you know me. I have your cell number Mm-hmm, so you can text me and you know that I know that you know that I know your cell number Right, right, and if I call you or text you the intention is that The intention is that you're going to respond, right? So like I know if I property changed You've made a change in a text box. It's changed a property the intention is that Somebody knows about it and acts accordingly. Yes, right? It's a more direct model, right? The intention is that you do something about it Yeah, and again that the intention isn't really part of the pattern, but yeah, that is the practical application of it, right? You send and receive one at a time Mm-hmm, so instead of I know that in texting you can have multiple recipients on a text, right? But this is more you text me you text while we go through the whole list of people. We're trying to organize dinner It's all one at a time. Yep, right, and it's like we've said direct communication, right? The pub sub model Is is different in a couple ways and I think they're significant So the sender and recipients don't know each other. I Send out once. Mm-hmm. It's a like a multicast delegate for example on net I just you send a text message or better yet you put a tweet out and I might see your tweet. I might not see your tweets Mm-hmm if I have filters set up and you're talking about Microsoft and something at work Like you guys have a baseball game or something while I'm filtering it out So I don't work for Microsoft, right? But if you're talking about getting together for dinner at C star or some other awesome restaurant here in Bellevue Then I want to receive that right. So there's an intermediary involved Right, and it's the third party. So that's when we talk about things like service boss or message broker Those types of things. Yep, and those are really the biggest differences and and again with the pub sub you publish people have subscribed but there's no Again, there's no expectation. I'm not writing the code with the intention that Once you broadcast Something or somebody has received that and then is notified. It's it's The message is out there you may do something with it you may save them up and do something later on there's really You know direct or indirect or almost immediate versus potentially delayed Is yeah, it's kind of the way I think about the two is that yeah No, I think that accurate There's also something that you can add on to the pub sub which is reliable messaging to make sure that actually gets there And you're still using an intermediary, right? But again, if we just talk about the two patterns, right? If I'm talking to somebody directly there is kind of an expectation that you're gonna do something right Can you meet me for dinner? Yes or no, right as opposed to sending out a broadcasting anybody who wants to meet for dinner We're going to this restaurant at seven o'clock, right? Yep, so and those are the biggest differences I don't know that anybody really writes their own pub sub because there's so many frameworks out there to do that Mm-hmm Or the observer pattern I think is very valuable to have in your toolkit right when you have to do that sort of one-to-one Notification yep and truth be told we do it all the time in dot-net probably without thinking about it with I notify property Changed mm-hmm subscribing to events and those types of things right and speaking of I notify property changed Now I didn't do a test for this because if you've been doing any sort of WPF or XAML then you're familiar with this Yeah, right, so here's the observer it subscribes to the property changed events and When that event gets fired Again the expectation is we're going to do something right update the UI, you know change something And that just is again driven by events So we have an event the property change event handler This is all built into the framework, and it's a perfect example right out of the box right of the observer pattern Yep, and and when you would use it and why yes Cool great all right So that's observer pattern and a little bit of pub sub and we'll see you next time on visual studio toolbox And we will continue our discussion of design patterns. Yeah, thanks for listening