Skip to content

Instantly share code, notes, and snippets.

@czyrux
Last active July 26, 2021 05:43
Show Gist options
  • Save czyrux/f2eff89628b6309761d9 to your computer and use it in GitHub Desktop.
Save czyrux/f2eff89628b6309761d9 to your computer and use it in GitHub Desktop.
PresenterLoader
import android.content.Context;
import android.support.v4.content.Loader;
public final class PresenterLoader<T extends Presenter> extends Loader<T>{
private final PresenterFactory<T> factory;
private T presenter;
public PresenterLoader(Context context, PresenterFactory<T> factory) {
super(context);
this.factory = factory;
}
@Override
protected void onStartLoading() {
// called on activity start
// if we already own an instance of our presenter, simply deliver it.
if (presenter != null) {
deliverResult(presenter);
return;
}
// Otherwise, force a load
forceLoad();
}
@Override
protected void onForceLoad() {
// Create the Presenter using the Factory
presenter = factory.create();
// Deliver the result
deliverResult(presenter);
}
@Override
protected void onReset() {
presenter.onDestroyed();
presenter = null;
}
}
public interface Presenter <V>{
void onViewAttached(V view);
void onViewDetached();
void onDestroyed();
}
/**
* Creates a Presenter object.
* @param <T> presenter type
*/
public interface PresenterFactory<T extends Presenter> {
T create();
}
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import de.czyrux.countrykata.ui.presenter.PresenterLoader;
public class SampleActivity extends AppCompatActivity implements SomeView, LoaderManager.LoaderCallbacks<SomePresenter> {
private static final int LOADER_ID = 101;
private SomePresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialization code...
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
@Override
protected void onStart() {
super.onStart();
// Ready to use presenter
presenter.onViewAttached(this);
}
@Override
protected void onStop() {
presenter.onViewDetached();
super.onStop();
}
// Some other activity code and view interface implementation...
@Override
public Loader<SomePresenter> onCreateLoader(int id, Bundle args) {
return new PresenterLoader<>(this, new SomePresenterFactory());
}
@Override
public void onLoadFinished(Loader<SomePresenter> loader, SomePresenter presenter) {
this.presenter = presenter;
}
@Override
public void onLoaderReset(Loader<SomePresenter> loader) {
presenter = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment