Skip to content

Instantly share code, notes, and snippets.

@jacquesgiraudel
Created March 16, 2016 06:29
Show Gist options
  • Save jacquesgiraudel/43ea55a668979712385b to your computer and use it in GitHub Desktop.
Save jacquesgiraudel/43ea55a668979712385b to your computer and use it in GitHub Desktop.
observer-snippet
public class ObserverActivity extends Activity implements Observer{
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
MyObservable myObservable = new MyObservable();
// Registering of the observer (here the activity)
myObservable.addObserver(this);
// Changing the state of the observable
myObservable.setValue("Hello ! ");
}
// Update of the observer on a state change notification
@Override
public void update(Observable observable, Object data) {
textView.setText(((MyObservable)observable).getValue());
}
class MyObservable extends Observable {
private String mValue;
public String getValue() {
return mValue;
}
public void setValue(String mValue) {
this.mValue = mValue;
// Mark the change of state
setChanged();
// Notification of the change for update
notifyObservers();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment