BrandGhost

Mastering the Observer Pattern with System.Reactive in #CSharp

In this tutorial, you'll learn how to use the System.Reactive Extensions (RX) for the Observer Pattern in Csharp. You'll learn how to create an Observable that sends notifications when a particular condition is met, and you'll see how to use the LINQ to Observable extension to query the observable for changes. This tutorial is perfect if you want to learn how to use the Observer Pattern in Csharp using the System.Reactive Extensions. Have you subscribed to my weekly newsletter yet? A 5-minute r...
View Transcript
all right so I'm here again to talk about the Observer pattern in C if you've been watching my channel you might be saying Nick how many ways can we possibly implement the Observer pattern we've already seen it done with events and event handlers as well as just having a dedicated Observer and an observable class and using an interface as an API between the two but there's another fun library that we can use to go implement this so in this video we're going to be looking at the system reactive nougat package and how we can implement the Observer pattern leveraging that and a super quick reminder before I head over to visual studio is to check out my weekly software engineering newsletter it's totally free you get software engineering topics and net topics as well as exclusive articles and early access to videos totally for free every week check for the link in the pin comments below and let's dive into visual studio all right on my screen I have an implementation of the Observer pattern using the system reactive nougat package a quick recap of the Observer pattern is that we have two things that we need to make it work one is going to be the Observer and the other is the observable so so that's these two classes that we have at the bottom of our file here now as their names suggest the Observer is going to be the thing that observes the observable and if that sounds like a mouthful what I mean by that is that the Observer is able to get notified from the observable when the observable decides that it wants to do notifications and those notifications could be basically anything you're thinking of it's some type of signal that you want to allow other things to watch for it could be as simple as a string or an integer or you can have your own complex type that you want your observable to be able to share out with The Observers now in this case I'm going to start with looking at this message that we're going to be passing around and it's really trivial I'm just using a record type that's called message and it has a body on it but the only reason I'm doing this is to show you that you can use things a little bit more complex than just a string and that means if we wanted a body maybe a title maybe we wanted to have a two and a from or whatever type of information on it like date times you name it we can go add that kind of information onto this record and that's what's going to be passed along in our observable pattern next let's look at the implementation of the Observer and what's an interesting change from this one compared to the other videos which by the way if you haven't watched them I'll put a link above right here and you can go check those out and then come back to this one but this Observer is implementing an ey Observer interface that takes in a type parameter of the message type that we declared but this ey Observer is not something that I've gone ahead and created this is in fact from the system reactive namespace so for that implementation we need to have an oncompleted onerror and on next method that we Implement you'll notice that I've just left on error as some comment we don't have anything that we're showing in this example however on next and on completed are both implemented in this context our Observer is a pretty simple class it doesn't really have any logic that's built into it for being able to do any observation but it does have the signatures that our observable is going to be able to call when it needs to and that's a really big deviation from the first example that we looked at with events and event handlers in those situations The Observer was responsible for wiring itself up to the event given this thing's event handler and because we don't have any of that in this code the responsibilities are completely reversed so with that said let's go check out the observable down below similarly this class is implemented an ey observable interface with a message type parameter but again this ey observable is not something that I've created it's built into system reactive and here's where the magic happens because we're going to be leveraging this type called subject which again is part of the system reactive Nate package and this subject class has all of the pieces we need to make an observable so we're going to go ahead and instantiate that on line 37 here right in the Constructor so that once this observable is created we're able to leverage the subject rate away in this case we just have a subscribe method right on our observable but you'll notice that something's kind of interesting about the Subscribe method and that's that it has a return type of ey disposable if you've watched the other videos that we looked at we don't really have anything like this they're just sort of a void implementation or we're using that plus equals syntax to add on an event handler so why the heck does this return an i disposable well that's so that you can go implement the using statement pattern and dispose of this subscription when you're done listening to the observable and to pause for just a moment I think that this is super cool in terms of how you use this because in the first version of this that we were looking at with events and event handlers I was saying that I do genuinely really like that plus equal syntax that we get with events and event handlers but one of the drawbacks is that people aren't really thinking about when to use minus equals to go unsubscribed so what ends up happening is that people have these objects that they think are going out of scope and perhaps they are but they're not really behind the scenes getting dereferenced and that's because their event handler is holding on to the object reference in which they're defined sometimes this is the trade-off that we get when we have things that feel a little bit magical in terms of syntax but in this particular case we have this subscribe method that gives us back a reference to an i disposable so whenever we're done with that subscription we just dispose of it and it unsubscribes for us okay let's head back to the code and check the rest so now that we've looked at this subscribe method and seen what this ID disposable will do for us and the publish method is pretty simple if we look inside of it all that it's doing is calling subject on next and that's interesting for us right because on next was the same signature that we had up here on our Observer it's not the same type right because this is an observer type and if I scroll back down we're calling on next on the subject but because this subject inside of the Subscribe implement ation is hooking up our observers this is all handled for us so in fact when we go to run this program what will happen is that when we publish a method that message is going to get passed into the subjects on next call and from there it will go through all of its registered observers that are inside of the subject and that will trigger this code here for on next now you might be wondering what on completed does I feel like on error is a little bit more obvious but you have to trigger it through the subject implementation but oncompleted is used when you're all done being able to publish from your Observer so truly when there's no more messages to publish from your Observer you can call on completed and that will allow every Observer to know that there's no more messages coming now if we look at the example code that I have above here you'll notice that I don't call on completed anywhere and that means that technically this call should never run I could perhaps make this observable class Implement I disposable and that means that when we go to dispose it I could essentially tell the subject that we want to call on complete let's go try that out all right with a quick little change here and probably a bug fix we're now calling dispose on the subject without this change what was happening was technically I was creating a subject instance here on Line 39 and because observable was never implementing I disposable itself nothing was ever going to get the chance to call the dispose method on the subject so in fact this is probably a better approach because we're creating a resource that needs to be disposed of so we should handle that with our own dispose method it's also a really good opportunity to say on completed for the subject and that will mean that this Observer here will finally get oncompleted called so let's go ahead and jam a using statement right on the front of this observable now so when we finally get to the end of the scope here we should end up seeing on completed get called all right and if we run the application as we might expect we see on next fired with hello world that was the first message that we provided then goodbye world because that was the second message that we provided and then finally we get this oncompleted is fired and that's because we ended up calling dispose implicitly through that using block so when the object went out of scope because it was part of the using statement that meant that it would call dispose and then call dispose on the subject which then in turn called oncompleted and that will conclude the life cycle for this Observer pattern using system reactive all right so that's three different ways that we've now looked at for implementing The Observer pattern and this was way number three if you haven't seen the two other videos part of my reason for putting this little series together is to show you that with design patterns there's many different ways that we can approach them they're design patterns not design rules right so there's different guidelines that we want to adhere to because they're supposed to help us for a particular particular purpose but that's just the framework for it we're able to fill out the implementation as we' like and it's just a reminder right that there's different tools for different purposes so whatever is going to fit your needs best at least in this case you've seen three different ways that you can go do it but this was only one design pattern that we looked at to be able to have some type of communication it was The Observer pattern but there's another really cool pattern that we can look at for communication and some of you might already know what this is but if you don't you can go watch this video next and check it out thanks and we'll see you next time

Frequently Asked Questions

What is the Observer pattern and how is it implemented in this video?

In this video, I explain the Observer pattern as a design pattern where we have two main components: the Observer and the Observable. The Observer watches for notifications from the Observable, which can send various types of signals. I demonstrate how to implement this pattern using the System.Reactive NuGet package, showcasing how to create an Observer class that implements the IObserver interface and an Observable class that utilizes the Subject class from the same package.

What are the advantages of using System.Reactive for the Observer pattern?

Using System.Reactive provides a more structured way to manage subscriptions compared to traditional event handlers. One key advantage is that the Subscribe method returns an IDisposable, allowing for easy cleanup of subscriptions when they're no longer needed. This helps prevent memory leaks, as you can dispose of the subscription explicitly, ensuring that resources are managed effectively.

How does the onCompleted method work in the Observer pattern implementation?

The onCompleted method is called when the Observable has finished sending messages and there are no more notifications to send. In my implementation, I show that we can call onCompleted when we dispose of the Observable, which signals to all Observers that they should stop listening for messages. This is an important part of managing the lifecycle of the Observer pattern, ensuring that resources are released properly.

These FAQs were generated by AI from the video transcript.
An error has occurred. This application may no longer respond until reloaded. Reload