Implementing Callback in Java

If you are a web developer and familiar with JavaScript, I guess you are also familiar with callback methodology. Callback is the heart of Javascript, because browser can only handle a single thread programming. See this for more details: Why Use Callback.

Well, I’m not here to tell you about Callback in JavaScript. In my current project I was assigned to build an Android mobile app. Which means I have to code in Java. But since in this recent years I often to code using JavaScript, this made me so JavaScript minded. Unlike JavaScript, in Java we can have multiple thread, and also asynchronous process within our program. See this: Java Multithreading.

But still, as a JavaScript centric programmer, I want a Callback to handle my asynchronous process, with common structure that easy to understand. So I came up to this idea to make a Callback in Java.

As every of you can guess, this Callback is basically an Interface that have to be implemented every time it being used. So for basic structure we can have like following.

public interface Callback {

public void finish(Object params);

public void error(Object params);
}

And for caller just have to give the return value to Callback like this.

public void fetchAPIData(Callback callback) {

String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
(DownloadManager.Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
callback.finish(response);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
callback.error(error);
}
});

RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsObjRequest);
}

For implementation is simple, such as following.

APIClass.fetchAPIData(new Callback() {
@Override
public void finish(JSONObject response) {
// operation finished handler goes here
}

@Override
public void error(VolleyError error) {
// error handler goes here
}
});

Hmm… It looks so impressive, but I think it’s not enough. How about we also implement Promises-like callback, that should be awesome.

To be continued. In next post I will discuss about how to implement Promise-like Callback.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.