IObserver and IObservable in C# for Observer vs Delegates, Events

前端 未结 2 1252
[愿得一人]
[愿得一人] 2020-12-25 07:55

All I am trying to do is implementing the observer pattern.

So, I came up with this solution:

We have a PoliceHeadQuarters whose primary job is to send noti

2条回答
  •  無奈伤痛
    2020-12-25 08:55

    Another suggestion - you probably want to consider leveraging the reactive extensions library for any code using IObservable. The nuget package is Rx-Main and the homepage for it is here: http://msdn.microsoft.com/en-us/data/gg577609.aspx

    This will save you a lot of boilerplate code. Here's a super simple example:

    var hq = new Subject();
    
    var inspectorSubscription = hq.Subscribe(
        m => Console.WriteLine("Inspector received: " + m));
    
    var subInspectorSubscription = hq.Subscribe(
        m => Console.WriteLine("Sub Inspector received: " + m));
    
    hq.OnNext("Catch Moriarty!");
    

    It will output:

    Inspector received: Catch Moriarty!
    Sub Inspector received: Catch Moriarty!
    

    Reactive Extensions is a big subject, and a very powerful library - worth investigating. I recommend the hands-on lab from the link above.

    You would probably want to embed those subscriptions within your Inspector, SubInspector immplementatinos to more closely reflect your code. But hopefully this gives you an insight into what you can do with Rx.

提交回复
热议问题