Saturday 14 April 2018

HB Blog 154: Observer Design Pattern Using Observable Class.

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. This class represents an observable object, or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed.
An observable object can have one or more observers. An observer may be any object that implements interface Observer. After an observable instance changes, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//CustomObservable.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.harshalbenake.observable;

import java.io.Serializable;
import java.util.Observable;

/**
 * Created by sonam.aslekar on 7/13/2018.
 */

public class CustomObservable extends Observable implements Serializable {

    private String data;

    public String getValue() {
        return data;
    }

    public void setValue(String data) {
        this.data = data;
        this.setChanged();
        this.notifyObservers(data);
    }
}

//MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.harshalbenake.observable;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private CustomObservable customObservable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create CustomObservable
        customObservable = new CustomObservable();
        // Set customObservable default value to Dummy Data
        customObservable.setValue("Dummy Data");
        // Create frag1
        MainFragment mainFragment = new MainFragment();
        Bundle args = new Bundle();
        // Put customObservable (That why CustomObservable implements Serializable)
        args.putSerializable(MainFragment.PARAM, customObservable);
        mainFragment.setArguments(args);
        // Add MainFragment on screen
        getFragmentManager().beginTransaction().add(R.id.ll_container, mainFragment).commit();
        final EditText edittext = (EditText) findViewById(R.id.edittext);
        edittext.setText(customObservable.getValue());
        // Add a button to change value of a dynamically
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set a new value in a customObservable
                customObservable.setValue(edittext.getText().toString());
            }
        });
    }
}

//MainFragment.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.harshalbenake.observable;


import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

public class MainFragment extends Fragment {
    public static final String PARAM = "param";
    private CustomObservable customObservable;
    TextView textView;
    public MainFragment() {
    }

    private Observer observer = new Observer() {
        @Override
        public void update(Observable observable, Object data) {
            // customObservable changed!
            // data is the customObservable data (it's the same as customObservable.getValue())
            textView.setText("Observer has changed to new data:\n" + data);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            // Get CustomObservable created in activity
            customObservable = (CustomObservable) getArguments().getSerializable(PARAM);
            // Add listener for value change
            customObservable.addObserver(observer);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        textView=(TextView)view.findViewById(R.id.textview);
        return view;
    }


}