Object Observer pattern in Android ?

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

          The objects which are watching the state changes are called observer. Alternatively observer are also called listener. The object which is being watched is called subject.

1.1 Example: View A is the subject. View A displays the temperature of a container.  View B display a green light is the temperature is above 20 degree Celsius. Therefore View B registers itself as a Listener to View A.  If the temperature of View A is changed an event is triggered. That is event is send to all registered listeners in this example View B. View B receives the changed data and can adjust his display.

1.2. Evaluation:  The subject can registered an unlimited number of observers. If a new listener should register at the subject no code change in the subject is necessary.

1.3 Source Code:

import java.util.Observable;
import java.util.Observer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ObjectObserverPattern extends Activity implements Observer,
        OnClickListener {
    BaseApp myBase;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myBase = (BaseApp) getApplication();
        myBase.getObserver().addObserver(this);
        // myBase.getObserver().setValue(10);

        btn = (Button) findViewById(R.id.button1);
        btn.setText("value: " + myBase.getObserver().getValue());
        btn.setOnClickListener(this);

    }

    @Override
    public void update(Observable observable, Object data) {
        // This method is notified after data changes.
        Toast.makeText(this, "I am notified" + myBase.getObserver().getValue(),
                0).show();
        btn.setText("value: " + myBase.getObserver().getValue());

    }

    @Override
    public void onClick(View v) {
        startActivity(new Intent(ObjectObserverPattern.this,
                SecondActivity.class));

    }
}

package com.ramesh.test.observerpattern;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SecondActivity extends Activity implements Observer,
        OnClickListener {
    BaseApp myBase;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myBase = (BaseApp) getApplication();
        myBase.getObserver().addObserver(this);
        btn = (Button) findViewById(R.id.button1);
        btn.setText("value: " + myBase.getObserver().getValue());
        btn.setOnClickListener(this);

    }

    @Override
    public void update(Observable observable, Object data) {
        // This method is notified after data changes.
        Toast.makeText(this, "I am notified" + myBase.getObserver().getValue(),
                0).show();
        btn.setText("value: " + myBase.getObserver().getValue());

    }

    @Override
    public void onClick(View v) {
        myBase.getObserver().setValue("After Value Changed!");
    }
}

public class Test extends Observable {
    private String name = "First time i have this Text";

    /**
     *@return the value
     */
    public String getValue() {
        return name;
    }

    /**
     *@param value
     * the value to set
     */
    public void setValue(String name) {
        this.name = name;
        setChanged();
        notifyObservers();
    }
}

package app.tabsample;

import android.app.Application;

public class BaseApp extends Application {
    Test mTest;

    @Override
    public void onCreate() {
        super.onCreate();

        mTest = new Test();
    }

    public Test getObserver() {
        return mTest;
    }

}
NOTE:
     In manifest make sure that add application.

You can download source code here.

More description avaible on Observer

Advertisements

5 thoughts on “Object Observer pattern in Android ?

  1. Thank you for this concise answer. What I am wondering about is this though: In your onCreate you register the activity with the observable. What I don’t see is how you unregister when your activity is gone. Say that that particular Activity is destroyed because you stayed in another activity long enough. Wouldn’t that yield to a reference to a now non existent object and ultimately lead to a crashing app or increasing memory use?

  2. Your example is quite helpful but most of the update connections happen on async threads that do not share connection between Observers and Observables. Most of the updates may occur inside time consuming processes that are better suited to be executed on other thread than the Main UI thread.
    On those cases there is no way to connect the Activity and the Observable in such this simple way because the “update()” code will then execute on the non-UI thead. There are solutions such as IntentService and Result/Broadcast Receivers but are not developed based on this Observer pattern.

  3. I came from a SO answer. This is really helpful when BroadcastReceiver is not enough for some situations. It really helped me, thank you for simple example and your post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s