Skip to content

Instantly share code, notes, and snippets.

@ZkHaider
Last active August 29, 2015 14:18
Show Gist options
  • Save ZkHaider/ddbd3589809b2c1b7a84 to your computer and use it in GitHub Desktop.
Save ZkHaider/ddbd3589809b2c1b7a84 to your computer and use it in GitHub Desktop.
Code Sample
/*
* In this example I am demonstrating a Network Operation using Retrofit, OkHttp, and Otto
* Using these libraries allows me to decouple things from the UI, and make calls to a
* sample REST API a alot easier. The key here is decoupling complex classes, making things
* easy to read, keeping things simple and separate, and so on.
*/
// Model class
public class CodeSample {
// Code should be simple and clean, easy to read, for similar variables just use similar names
private String mSample;
public CodeSample(String sample) {
this.mSample = sample;
}
public String getSample() {
return mSample;
}
public void setSample(String sample) {
this.mSample = sample;
}
}
// Our Retrofit Interface for getting Code from an API, we keep interfaces separate
// To decouple complexities
public interface IOtherCode {
@GET("/othercode.json")
void getCodeSample(Callback<CodeSample> callback);
}
/*
* Keep complexities separate, so a network client class is separate from
* the manager that manages calls to that client
*/
public class CodeClient {
// A sample network client class, we use a singleton pattern here
private static CodeClient sCodeClient;
private RestAdapter mAsyncRestAdapter;
private static final String API_URL = "https://codesample.com/api/v1";
private CodeClient() {
mAsyncRestAdapter = RestAdapter.Builder()
.setEndpoint(API_URL)
.setClient(new OkClient(new OkHttpClient()));
.build();
}
// We can pass in context if we choose to, I am leaving that out
public static CodeClient getClient() {
if (sCodeClient == null)
sCodeClient = new CodeClient();
return sCodeClient;
}
public void getOtherCode(Callback<CodeSample> callback) {
IOtherCode otherCodeInterface = mAsyncRestAdapter.create(IOtherCode.class);
otherCodeInterface.getCodeSample(callback);
}
}
/* A separate CodeSampleManager class manages these calls
* Use an event driven bus system like Otto (also made by SQUARE) to handle
* events and decouple things.
*/
public class CodeSampleManager {
private CodeClient sCodeClient;
// Again we can choose to pass in context but leaving it out
public CodeSampleManager() {
sCodeClient = CodeClient.getClient();
}
@Subscribe
public void getCodeSample(LoadCodeSampleEvent loadCodeSampleEvent) {
Callback<CodeSample> callback = new Callback<CodeSample>() {
@Override
public void success(CodeSample codeSample, Response response) {
// Collect the CodeSample and pass it into the UI using Otto
}
@Override
public void failure(RetrofitError retrofitError) {
// Do something with the error like display a message to the user
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment