Last active
June 1, 2016 13:55
-
-
Save pivotaljohn/67a4ecb84f57aad19cf81031c8b0bbaf 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.example.features; | |
import android.os.AsyncTask; | |
import android.support.annotation.VisibleForTesting; | |
/** | |
* @param <ARG> the type of arguments that can be passed in when executing this use case. | |
* @param <RESULT> the type of the outcome generated by this use case and passed its callback. | |
*/ | |
public abstract class UseCase<ARG, RESULT> { | |
/* | |
If we generify the calling code within this base class, it will force subclasses to | |
explicitly define types for each generic type. In this case, that's really unnecessary | |
and adds a bunch of boilerplate to each and every sub-type. | |
We've opted to, instead, ignore warnings about unchecked invocations. | |
So as to not get carried away, we comment each "offending" statement, not this whole class. | |
*/ | |
/** | |
* The implementation of this use case. | |
* | |
* @param args the same arguments passed into {@link #execute(Callback, Object[])} | |
* @return the return value that should be passed to callbacks of this UseCase. | |
*/ | |
public abstract RESULT run(final ARG... args); | |
public interface Callback<RESULT> { | |
void execute(RESULT result); | |
} | |
public UseCaseTask execute(final Callback callback, final ARG... args) { | |
//noinspection unchecked | |
return newUseCaseTask().execute(callback, args); | |
} | |
protected UseCaseTask newUseCaseTask() { | |
return new AsyncUseCaseTask(); | |
} | |
private class AsyncUseCaseTask implements UseCaseTask<ARG> { | |
private AsyncTask<ARG, Void, RESULT> mAsyncTask; | |
private Callback mCallback; | |
@SafeVarargs | |
@Override | |
public final UseCaseTask execute(final Callback callback, final ARG... args) { | |
mCallback = callback; | |
mAsyncTask = new AsyncTask<ARG, Void, RESULT>() { | |
@SafeVarargs | |
@Override | |
protected final RESULT doInBackground(final ARG... args1) { | |
return UseCase.this.run(args1); | |
} | |
@Override | |
public void onPostExecute(final RESULT result) { | |
// noinspection unchecked | |
mCallback.execute(result); | |
} | |
}; | |
mAsyncTask = mAsyncTask.execute(args); | |
return this; | |
} | |
@Override | |
public boolean cancel(final boolean mayInterruptIfRunning) { | |
return mAsyncTask.cancel(mayInterruptIfRunning); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment