Last active
March 29, 2017 09:42
-
-
Save twogood/cc4f008cf9e90911d3e1d2dbcce2b7f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new Lova<Integer, TowerMetadata>(id -> towersHttpClient.retrieveTowerMetadata(id)) | |
.onSuccess(this::showTowerMetadata) | |
.onError(this::displayError) | |
.execute(towerId); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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