Objects in java have a particular state at any given instance during run time of a program.

Android echosystem consists of mechanism in which different objects work together wile reacting to each other’s change in state.


 

Let us take an example :

EditText is a ‘View’ object and it has a property ‘text’ which can change during run time, In android we have a TextWatcher object which will react to EditText’s change in state with respect to property ‘text’.

EditText edt = new EditText(someContext);

TextWatcher watcher = new TextWatcher(){

 

public void onTextChanged(CharSequence s){

// react to this text change state of edt .

}

};

eat.addOnTextChangeListener(watcher); // binding an observer with //this objects’s state


 

  • Observer Pattern : Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Usage :

Use observer pattern in code when it is needed to react to some event(like use some output,changed value,or perform some action when that event triggers)

Event can be defined as change in object’s state or completion of some operation which needs to be notified.

E.g. Button’s ‘OnClick’ denotes Button is in “Clicked” state.

“NextText” event in XMLPullParser is the event when a text is encountered during parsing.

A simple observer implementation :

Assume your activity needs a parsed JSON result :

Step 1:

Create a Json Parser class :

class JsonParser{

//this class parse json somehow, using Gson,Jackson,JsonObject etc …

}

Step 2 :

Create an interface which has method to carry parsing result,this is our Observer interface.

interface JsonResultObserver{

void onParseResult(SomeObject result);

}

Step 3:

Add JsonResultObserver as dependency to JsonParser

 

class JsonParser{

//this class parse json somehow, using Gson,Jackson,JsonObject etc …

public static void parseJson(String son,JsonResultObserver observer){

// parse json string into some object and call the observer’s //onParseResult

observer.onParseResult(result);

}

}

Step 4:

Implement interface in your activity and call the parser.

class MyActivity extends Activity implements JsonResultObserver{

JsonParser.parseJson(someJsonString,this);// this = current  //instance of activity as

@Override

public void onParseResult(SomeObject result){

// this method is called when JsonParser.parseJson completes

….

 

}

 

}


 

 

Leave a Reply

Your email address will not be published. Required fields are marked *