Tal32422
Tal32422

Reputation: 11

Trying to build a simple Observer-Observable

I'm trying to build a simple Observer-Observable and when I call the notifyObservers();, it doesn't work and keeps on. Someone knows what to do?

Class P:

import java.util.Observable;

public class P extends Observable{
   public void func(){
       notifyObservers();       
   }

}

Class Ob:

import java.util.Observable;
import java.util.Observer;

public class Ob implements Observer{

    P p;
    public Ob(P p) {
        this.p=p;
    }

    public void run(){

        p.func();

    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("SUceesssed");
    }

}

Run:

public class run {

    public static void main(String[] args) {

    P p=new P();

        Ob o=new Ob(p);
        p.addObserver(o);
        o.run();
    }

}

Upvotes: 1

Views: 65

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35011

You have to call hasChanged() before notifying the observers

  public class P extends Observable{
   public void func(){
     hasChanged();
     notifyObservers();
   }

 }

Upvotes: 3

Related Questions