Skip to content

Instantly share code, notes, and snippets.

@akexorcist
Last active August 29, 2015 14:20
Show Gist options
  • Save akexorcist/0894b754f95c89623391 to your computer and use it in GitHub Desktop.
Save akexorcist/0894b754f95c89623391 to your computer and use it in GitHub Desktop.
Call service with delegate
public class CallServiceRunnable extends SomeRunnable {
private SomeProviderDelegate delegate;
private SomeException exception;
private SomeObject object;
public CheckMSISDNRunnable(SomeProviderDelegate delegate) {
super(httpClient);
this.delegate = delegate;
}
@Override
public void run() {
String url = getUrl();
HttpUriRequest uriRequest = createJSONGetRequest(url);
try {
JSONObject root = sendJSONRequest(uriRequest);
if (root == null) {
throw new SomeException(SomeExceptionCode.BadJSONResponse);
}
SomeParser parser = new SomeParser();
object = parser.parseObject(root);
sendSuccessMessage();
} catch (SomeException exception) {
exception = exception;
sendFailureMessage();
}
}
private String getUrl() {
return getSomeUrl();
}
@Override
protected void success() {
try {
delegate.onSuccess(object);
} catch (IllegalStateException e) { }
}
@Override
protected void failure() {
assert failure != null;
try {
delegate.onFailed(exception);
} catch (IllegalStateException e) { }
}
}
public onCreate(...) {
...
...
SomeManager manager = SomeManager.managerWithDelegate(managerDelegate);
manager.callService();
}
SomeManager.SomeManagerDelegate managerDelegate = new SomeManager.SomeManagerDelegate() {
public void onSuccess(SomeObject object) {
// Do something
}
public void onFailed(SomeException exception) {
// Do something
}
}
public class SomeManager implements SomeProviderDelegate {
private AuthManagerDelegate delegate;
public AuthManager(AuthManagerDelegate delegate) {
this.delegate = delegate;
}
public void callService() {
SomeProviderFactory.getSomeProviderFactory().callThatService(this);
}
@Override
public void onSuccess(SomeObject object) {
this.delegate.onSuccess(object);
}
@Override
public void onFailed(SomeException exception) {
this.delegate.onFailed(exception);
}
...
}
public interface SomeProviderDelegate {
public void onSuccess(SomeObject object);
public void onFailed(SomeException exception);
...
}
public class SomeProviderFactory {
private static SomeProviderInterface providerInterface;
public synchronized static SomeProviderInterface getSomeProviderFactory() {
if (providerInterface == null) {
providerInterface = new SomeProvider();
}
return providerInterface;
}
}
public interface SomeProviderInterface {
public void callService(SomeProviderDelegate delegate);
,,,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment