Skip to content

Instantly share code, notes, and snippets.

@Kane-Shih
Created December 24, 2015 04:26
Show Gist options
  • Save Kane-Shih/8518fba447993991c14d to your computer and use it in GitHub Desktop.
Save Kane-Shih/8518fba447993991c14d to your computer and use it in GitHub Desktop.
import java.util.*;
public class PromisePipeTest {
static boolean isOver = false;
public static void main(String[] args) {
Promise p1 = new Promise("p1");
Promise p2 = new Promise("p2");
Promise p21 = new Promise("p2-1");
Promise p211 = new Promise("p2-1-1");
Promise p22 = new Promise("p2-2");
Promise p3 = new Promise("p3");
p1.pipe(p2.pipe(p21.pipe(p211)).pipe(p22)).pipe(p3).exec(new Callback() {
@Override
public void onResult(String result) {
log("ok cb: " + result);
isOver = true;
}
}, new Callback() {
@Override
public void onResult(String result) {
log("fail cb: " + result);
isOver = true;
}
});
while(!isOver) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
}
}
log(p1.result);
log(p2.result);
log(p21.result);
log(p211.result);
log(p22.result);
log(p3.result);
}
static class Promise {
String name;
String result = null;
Promise next;
public Promise(String name) {
this.name = name;
}
public Promise pipe(Promise newNext) {
if (next == null) {
next = newNext;
} else {
Promise theNextWithoutNext = next;
while (theNextWithoutNext.next != null) {
theNextWithoutNext = theNextWithoutNext.next;
}
theNextWithoutNext.next = newNext;
}
return this;
}
public Promise exec(final Callback allOk, final Callback fail) {
new Thread(name) {
@Override
public void run() {
try {
sleep(100);
} catch (InterruptedException e) {
}
Promise.this.result = (new Random().nextInt(2) > 0) ? getName() + " is done" : null;
log(Promise.this.result);
if (Promise.this.result == null) {
fail.onResult(getName() + " is failed");
} else {
if (Promise.this.next != null) {
log("NEXT");
Promise.this.next.exec(allOk, fail);
} else {
log("END");
allOk.onResult("ALL DONE");
}
}
}
}.start();
return this;
}
}
public static void log(Object o) {
System.out.println(o == null? "null" : o.toString());
}
interface Callback {
void onResult(String result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment