package com.claimtowers.common.asynctask; | |
public class AsyncTaskResult<T> { | |
private T result; | |
private Exception exception; | |
public AsyncTaskResult(T result) { | |
this.result = result; | |
} | |
public AsyncTaskResult(Exception exception) { | |
this.exception = exception; | |
} | |
public T getResult() { | |
return result; | |
} | |
public Exception getException() { | |
return exception; | |
} | |
} |
new Lova<Integer, TowerMetadata>(id -> towersHttpClient.retrieveTowerMetadata(id)) | |
.onSuccess(this::showTowerMetadata) | |
.onError(this::displayError) | |
.execute(towerId); |
package com.claimtowers.common.asynctask; | |
import android.os.AsyncTask; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public class Lova<Param, Result> extends AsyncTask<Param, Void, AsyncTaskResult<Result>> { | |
private final Function<Param, Result> function; | |
private Consumer<Result> consumer; | |
private Consumer<Exception> errorHandler; | |
public Lova(Function<Param, Result> function) { | |
this.function = function; | |
} | |
public Lova<Param, Result> onSuccess(Consumer<Result> consumer) { | |
this.consumer = consumer; | |
return this; | |
} | |
public Lova<Param, Result> onError(Consumer<Exception> errorHandler) { | |
this.errorHandler = errorHandler; | |
return this; | |
} | |
@Override | |
protected AsyncTaskResult<Result> doInBackground(Param... params) { | |
try { | |
return new AsyncTaskResult<>(function.apply(params[0])); | |
} catch (Exception e) { | |
cancel(false); | |
return new AsyncTaskResult<>(e); | |
} | |
} | |
@Override | |
protected void onPostExecute(AsyncTaskResult<Result> asyncTaskResult) { | |
super.onPostExecute(asyncTaskResult); | |
consumer.accept(asyncTaskResult.getResult()); | |
} | |
@Override | |
protected void onCancelled(AsyncTaskResult<Result> asyncTaskResult) { | |
super.onCancelled(asyncTaskResult); | |
errorHandler.accept(asyncTaskResult.getException()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment