2. Callbacks
A callback is a piece of executable code that
is passed as an argument to other code,
which is expected to call back ( execute )
the argument at some convenient time
— Wikipedia
3. Promises & Deferreds: WTF?
Promises are a programming construct that
have been around since 1976.
A promise represents a value that is not yet
known
A deferred represents work that is not yet
finished
5. Why/When should I use the Deferred Object
/ Promise pattern?
DeferredObject/Promise pattern can help
you to better organise your code,
especially the asynchronous type
6. it also makes it really easy to merge and
pipe the execution of different pieces of
asynchronous code, which otherwise
would get really messy to code.
7. Normal case
new DeferredAsyncTask<HttpResponse,HttpResponse,Void>() {
protected abstract Resolved doInBackground() throws Exception {
//do your async code here
}
}
.done( new ResolveCallback<HttpResponse> {
public void onResolve(HttpResponse resolved) {
//your success code here
}
})
.fail ( new RejectCallback<HttpResponse> {
public void onReject(HttpResponse rejected) {
//your failure code here
}
});
8. Several promises
Promise<A1,B1,C1> p1 = new DeferredAsyncTask<A1,B1,C1>() { ... };
Promise<A2,B2,C2> p1 = new DeferredAsyncTask<A2,B2,C2>() { ... };
Promise<A3,B3,C3> p3 = new DeferredAsyncTask<A3,B3,C3>() { ... };
//when gives you a new promise that gets triggered when all the merged promises are resolved or one of them fails
DeferredObject.when(p1,p2,p3)
.done(new ResolveCallback<MergedPromiseResult3<A1,A2,A3>() {
public void onResolve(MergedPromiseResult3<A1,A2,A3> resolved){
Log.i(TAG, "got: " + resolved.first() + resolved.second() + resolved.third());
}
})
9. .fail(new RejectCallback<MergedPromiseReject>() {
public void onReject(MergedPromiseReject rejected) {
//failure handling here
}
})
.progress(new ProgressCallback<MergedPromiseProgress>() {
public void onProgress(final MergedPromiseProgress progress){
//you get notified as the merged promises keep coming in
}
});
//Merging doesn't stop you do add individual callbacks for promises that are in the merge
p1.done(...).fail(...)
//Or even merging them in another way
DeferredObject.when(p1,p2).done(...).fail(...)
10. new DeferredAsyncTask<HttpResponse,HttpResponse,Void>() {...}
.done( /* callback to first call here */ )
.pipe(new ResolvePipe<HttpResponse,HttpResponse,Void>() {
public Promise<HttpResponse,HttpResponse,Void> pipeResolved(HttpResponse response1){
return new DeferredAsyncTask<HttpResponse,HttpResponse,Void>() { ... }
}
})
.done( /* callback to second call here */ )
.pipe(new ResolvePipe<HttpResponse,HttpResponse,Void>() {
public Promise<HttpResponse,HttpResponse,Void> pipeResolved(HttpResponse response1){
return new DeferredAsyncTask<HttpResponse,HttpResponse,Void>() { ... }
}
})
.done( /* callback to third call here */ )