0

I'm toying a bit with IObservable and IObserver in C# after using it's Java equivalent. However I'm not entirely sure how to use it correctly. I've Googled this, but the results are either too problem-specific or way too unnecessarily complex.

This is my very basic Java code :

public class SomeController extends Observable{

    public void doSomething()
    {
        //dostuff
        setChanged();
        notifyObservers();
    }

}

public class SomeView implements Observer{

    private SomeController controller;

    public SomeView (SomeController ctrl)
    {
        this.controller= ctrl;
        ctrl.addObserver(this);
    }

    public void update (Observable o,Object arg)
    {
        if (o==controller)
        System.out.println("Update detected");
    }

}

Right, so how do I do the very exact same thing in C#?

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
Cata Visan
  • 91
  • 2
  • 3
  • 13

3 Answers3

3

C# has built-in support for the observer pattern, in the form of events. I think this is what you're looking for.

public delegate void UpdatedEventHandler(object sender, EventArgs e);

public class SomeController {

    public event UpdatedEventHandler Updated;

    protected virtual void OnUpdated(EventArgs e) 
    {
        if (Updated != null)
        {
            this.Updated(this, e);
        }
    }

    public void DoSomething()
    {
        // Do stuff

        this.OnUpdated(new EventArgs());
    }
}

public class SomeView implements Observer{

    private SomeController controller;

    public SomeView(SomeController ctrl)
    {
        this.controller = ctrl;
        ctrl.Changed += this.OnControllerChanged;
    }

    private void OnControllerChanged(object sender, EventArgs e)
    {
        if (sender == this.controller)
        {
            Console.WriteLine("Update detected");
        }
    }
}

In C#, IObservable and IObserver primarily appear as part of Reactive Extensions (Rx), to represent asynchronous observable sequences and event listeners.

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
0

C# has events a delegates.

Check out http://blog.monstuff.com/archives/000040.html

But as Observable is just an interface you could make a replica of the java-way if you want.

0

Are you talking about INotifyPropertyChanged implementation?
Here's an exemple : INotifyPropertyChanged exemple
In this case, you should probably use MVVM patern instead of MVC : Mvvm post
Hope this helps

Community
  • 1
  • 1
anthoLB29
  • 105
  • 1
  • 9