Introduction
It gets really hard to centralize all async-activity in one place.
Guit have 3 abstracts classes to solve this problem: AbstractAsyncCallback, AbstractRunAsyncCallback and AbstractRequestCallback.
Code
/**
* IMPORTANT: Do not save an instance of this class. <br/>
* It is designed to be instantiated at the time you use it. <br/>
* Otherwise the AsyncActivityEvent will get fired wrong.
*/
public abstract class AbstractAsyncCallback<T> implements AsyncCallback<T>, CommandSerializable {
private static final EventBus eventBus = BaseEntryPoint.getEventBus();
public AbstractAsyncCallback() {
eventBus.fireEvent(AsyncActivityEvent.START);
}
public final void onSuccess(T result) {
eventBus.fireEvent(AsyncActivityEvent.END);
success(result);
};
public abstract void success(T result);
@Override
public final void onFailure(Throwable caught) {
eventBus.fireEvent(AsyncActivityEvent.END);
eventBus.fireEvent(new AsyncExceptionEvent(caught));
failure(caught);
}
public void failure(Throwable caught) {
}
}/**
* IMPORTANT: Do not save an instance of this class. <br/>
* It is designed to be instantiated at the time you use it. <br/>
* Otherwise the AsyncActivityEvent will get fired wrong.
*/
public abstract class AbstractRunAsyncCallback implements RunAsyncCallback {
private static final EventBus eventBus = BaseEntryPoint.getEventBus();
public AbstractRunAsyncCallback() {
eventBus.fireEvent(AsyncActivityEvent.START);
}
@Override
public final void onSuccess() {
eventBus.fireEvent(AsyncActivityEvent.END);
success();
}
public abstract void success();
@Override
public final void onFailure(Throwable caught) {
eventBus.fireEvent(AsyncActivityEvent.END);
eventBus.fireEvent(new AsyncExceptionEvent(caught));
failure(caught);
}
public void failure(Throwable caught) {
}
}/**
* IMPORTANT: Do not save an instance of this class. <br/>
* It is designed to be instantiated at the time you use it. <br/>
* Otherwise the AsyncActivityEvent will get fired wrong.
*/
public abstract class AbstractRequestCallback implements RequestCallback {
private static final EventBus eventBus = GuitEntryPoint.getEventBus();
public AbstractRequestCallback() {
eventBus.fireEvent(AsyncActivityEvent.START);
}
public void failure(Request request, Throwable caught) {
}
@Override
public void onError(Request request, Throwable exception) {
eventBus.fireEvent(AsyncActivityEvent.END);
eventBus.fireEvent(new AsyncExceptionEvent(exception));
failure(request, exception);
}
@Override
public void onResponseReceived(Request request, Response response) {
eventBus.fireEvent(AsyncActivityEvent.END);
success(request, response);
}
public abstract void success(Request request, Response response);
}Async activity
If you use these two classes every time you make an async call, you will get your async-activity centralized.
You can subscribe to AsyncActivityEvent and AsyncExceptionEvent at any place in your application.