jamanji
jamanji

Reputation: 17

Best approach to writing a network class

I want to write a class that handles all my network interaction called NetworkManager. So using an instance of this class I'd have something like:

NetworkManager nm = new NetworkManager();
...
nm.login(username, password);
...

However, what is the best approach so this network manager can do something on the UI thread once some response has been received? Modelling on a onClick style event I think this would be like:

nm.getPicture(new NetworkListener() {
    @Override
    public void run(Picture p){
        updateUI(p);
    }

Where I am unsure how to write the getPicture method and the NetworkListener() class.

I don't want to use AsyncTask, because this would mean I'd have to write the server code at different parts of the MainActivity. I have also considered a broadcaster and a listener, but this seems too much for a one off event.

Upvotes: 0

Views: 97

Answers (1)

Alécio Carvalho
Alécio Carvalho

Reputation: 13657

Checkout Retrofit (http://square.github.io/retrofit/) it might be useful to consider for integrating the part of your network class. I'm not sure if you will have multiple similar calls, but if so, I would advice you to apply the Observer pattern, where you make the call and wait for the response asynchronously, yet, there's a nice library to accomplish that, very well documented, called Otto (http://square.github.io/otto/).

Upvotes: 1

Related Questions