12/08/2018, 15:16

Observer Design Pattern in Android and IOS development

Do you know Observer Design Pattern in software development? How to implement this pattern into your project? In this article I will show you the meaning of this pattern and the way to apply it in both swift and android code. I. Definition The observer pattern defines a one-to-many dependency ...

Do you know Observer Design Pattern in software development? How to implement this pattern into your project? In this article I will show you the meaning of this pattern and the way to apply it in both swift and android code.

I. 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 object which is being watched is called the subject. The objects which are watching the state changes are called observers or listeners.

So Observer is listener which is used very popular in Java development, or call it delegate in ios.

II. Observer in use

1. Android

We create a listener interface named "ProjectResult" as followings:

public interface ProjectResult{
        void onError();
        void onSuccess(List<Project> projects);
 }

Then we have a method with network request to get data, here i'm using volley library to get all project of framgia:

public static void getProjectInfo(final ProjectResult projectResult){
        String url = "";
        StringRequest request = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Type type = new TypeToken<List<Project>>(){}.getType();
                List<Project> projects = new Gson().fromJson(response, type);
                projectResult.onSuccess(projects);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                projectResult.onError();
            }
        });
}

You can see in above code block we used ProjectResult to get the result of request and put data in it (onSuccess, onError methods)

And in your activity (dialog, view or anywhere you use this request to get data), you need implement ProjectResult listener

public class MainActivity extends AppCompatActivity implements ApiService.ProjectResult {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ApiService.getProjectInfo(this);
    }

    @Override
    public void onError() {
        //show dialog error here
    }

    @Override
    public void onSuccess(List<Project> projects) {
        // your data from api here
    }
}

2.Swift

It's not like android code, in swift we using Protocol not Interface, and we also create a protocol like this:

protocol ProjectResult {
    func onError()
    func onSuccess(response: [ProjectResponse]!)
}

You can see the structure and syntax same as with java code above. It's really interesting.

And you can use it to handle data which return from your api request, here, we not use volley, we use Alamofire library.

static func getProjectInfo(delegate: ProjecInfoResult?){
        let url = ""
        Alamofire.request(url, method: .get, parameters:
            nil, encoding: JSONEncoding.default, headers: headerAuthen()).responseJSON{
                (response) -> Void in
                guard response.result.isSuccess else{
                    delegate?.onError()
                    return
                }
                let json = JSON(response.result.value as Any)
                delegate?.onSuccess(response: json.arrayValue.map({ Project(json: $0) }))
        }
}

And implenment in your controller or anywhere you want to handle data from api request

class MainProjectController : BaseTableController, ProjectResult{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ApiService.getProjectInfo(delegate: self)
    }
    func onError() {
        // show dialog error here
    }
    func onSuccess(response: [ProjectResponse]!) {
        // handle your data here
    }
}

III. Conclusion

So, Android and IOS is look similar and very simple in use. Now I hope you can code both android and ios without much knowledge of os language. Be ready to become a full-stack developer, you can code anything, any language you want.

0