0
我有一種情況,我需要用Callable創建一個FutureTask,檢查它的所有者是否已被取消。我的代碼看起來是這樣的:FutureTask with Callable引用FutureTask
public static FutureTask<Result> makeFuture(final Call call, final TaskCompletionCallback completion) {
return new FutureTask<Result>(new Callable<Result>() {
@Override
public Result call() throws Exception {
Result result = CYLib.doNetworkRequest(call, new CarryOnCallback() {
@Override
public boolean shouldCarryOn() {
return !FutureTask.isDone();
}
});
return result;
}
});
}
基本上doNetworkRequest
詢問CarryOnCallback
是否應該在操作過程中繼續在特定的時間。我想要回調看是否取消了FutureTask
,即調用doNetworkRequest
,這涉及查詢實際的FutureTask
對象。
現在我知道你不能真的訪問'this',因爲它還沒有被構造。但是有沒有解決這個問題的方法,或者針對我的情況有更好的設計?
乾杯
編輯:
好了,所以我繞了現在這個樣子。製作了一個自定義Callable和FutureTask。可調用保存到FutureTask的引用,這可以手動創建一個新的可贖回後才能進行設置:
public static MyTask makeMyTask(final Call call, final TaskCompletionCallback completion) {
MyTask task = null;
MyTask.InnerCallable innerCallable = new MyTask.InnerCallable(call, completion);
task = new MyTask(innerCallable);
innerCallable.setParent(task);
return task;
}
而只是參考,InnerCallable
看起來是這樣的:
public static class MyTask extends FutureTask<Result> {
InnerCallable callable;
public MyTask(InnerCallable callable) {
super(callable);
this.callable = callable;
}
private static class InnerCallable implements Callable<Result> {
private final Call call;
private final TaskCompletionCallback completion;
private WeakReference<MyTask> parentTask;
InnerCallable(Call call, TaskCompletionCallback completion) {
this.call = call;
this.completion = completion;
}
@Override
public Result call() {
Result result = CYLib.doNetworkRequest(this.call, new CarryOnCallback() {
@Override
public boolean shouldCarryOn() {
MyTask task = parentTask.get();
return !(task == null || task.isCancelled());
}
});
return result;
}
private void setParent(MyTask parentTask) {
this.parentTask = new WeakReference<MyTask>(parentTask);
}
}
}
好了,所以我通過添加'Object'參數到'CarryOnCallback'構造,改變了'CarryOnCallback'到一個抽象類,使調用'shouldCarryOn'和代理方法一種hackishly解決了這個通過上下文'Object'。所以上面的代碼現在成爲'... doNetworkRequest(call,new CarryOnCallback(this)...' – aliak
好吧,失敗...'ClassCastException'因爲'CarryOnCallback(this)'中的this不是外部FutureTask objet: /所以回到原點。 – aliak