GithubHelp home page GithubHelp logo

loadie's Introduction

Loadie

Maven Central

Loaders for the rest of us.

The concept of loaders in Android is pretty great: a way to do async work in a lifecycle-aware way. Unfortunately, the implementation is pretty bad. Loadie attempts to fix this in several ways:

  • Very simple loader interface for implementing a loader, only 3 possible methods to override. Compare that to Android loader's 6.
  • A clear separation between creating loaders and starting them.
  • Not tied into any component, you just need to call the 4 lifecycle methods on LoaderManager at the correct time, though default implementations for Activities and Fragments are provided.
  • Callback when the loader starts running so you can update your ui.
  • Explicit error handline with onLoaderError().
  • Results are always delivered async, so you don't have to guess when the callbacks are called vs your view setup logic.

Download

// Base lib
compile 'me.tatarka.loadie:loadie:0.2'
// LoaderMangerProvider for Activity and Fragment
compile 'me.tatarka.loadie:loadie-components:0.2'
// LoaderManagerProvider for Conductor
compile 'me.tatarka.loadie:loadie-conductor:0.2'
// AsyncTaskLoader and CursorLoader
compile 'me.tatarka.loadie:loadie-support:0.2'
// RxLoader
compile 'me.tatarka.loadie:loadie-rx:0.2'
// LoaderTester
androidTestCompile 'me.tatarka.loadie:loadie-test:0.2'

Creating a Loader

To create a loader, you subclass Loader and implement onStart() and optionally onCancel() and onDestroy().

public class MyLoader extends Loader<String> {
    // Convenience creator for loaderManager.init()
    public static final Create<MyLoader> CREATE = new Create<MyLoader>() {
        @Override
        public MyLoader create() {
            return new MyLoader();
        }
    };

    @Override
    protected void onStart(Receiver receiver) {
        // Note loader doesn't handle threading, you have to do that yourself.
        api.doAsync(new ApiCallback() {
            public void onResult(String result) {
                // Make sure this happens on the main thread!
                receiver.success(result);
            }
          
            public void onError(Error error) {
                receiver.error(error); 
            }
        });
    }

    // Overriding this method is optional, but if you can cancel your call when it's no longer needed, you should.
    @Override
    protected void onCancel() {
        api.cancel();
    }

    // Overriding this method is optional and allows you to clean up any resources.
    @Override
    protected void onDestroy() {

    }
}

In your async operation you call Receiver#result(value) as many times as you have results and then either Receiver#success() or Receiver#error(error) exactly once to notify the work has ended or there was an error. If you have used rxjava this contract should seem familer. There is also a convenience Receiver#success(value) when you only have a single value to deliver.

As mentioned above, loaders don't to any threading for you. You are responsible for getting the work off the main thread and delivering the results back to the main thread.

Using a Loader

It most cases you will manage loaders through a LoaderManager that you obtain from a LoaderManagerProvider. This will manage the lifecycle for you, ensuring your callbacks happen when they need to. For example, using me.tatarka.loadie:loadie-components and in an Activity, you would do:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LoaderManager loaderManager = LoaderManagerProvider.forActivity(this);
        // Creates a new loader or returns an existing one if it's already created.
        final MyLoader myLoader = loaderManager.init(0, MyLoader.CREATE, new Loader.CallbacksAdapter<String>() {
            @Override
            public void onLoaderStart() {
                // Update your ui to show you are loading something
            }

            @Override
            public void onLoaderResult(String result) {
                // Update your ui with the result
            }
            
            @Override
            public void onLoaderError(Throwable error) {
                // Update your ui with the error
            }

            @Override
            public void onLoaderComplete() {
                // Optionally do something when the loader has completed
            }
        });
        // The loader won't actually run until you call this!
        myLoader.start();
        
        setContentView(R.layout.activity_main);
        // view setup stuff...
        
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // The separation between initialization and starting, means it's easy to react to user events!
                myLoader.restart();
            }
        });
    }
}

me.tatarka.loadie:loadie-conductor has a LoaderManagerProvider for Conductor if that's your thing. It will ensure that the callbacks are not run when the view is not attached.

public class MyController extends Controller {

    LoaderManager loaderManager;

    public TestController() {
        loaderManager = LoaderManagerProvider.forController(this);
    }

    @NonNull
    @Override
    protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
        return ...;
    }
}

Built-in Loaders

There are a few built-in loaders for some common cases. me.tatarka.loadie:loadie-support has loaders that mirror the ones in the support lib.

public class MyAsyncTaskLoader extends AsyncTaskLoader<String> {
    @Override
    protected String doInBackground() {
        // Do lots of work to get a string.
        return "Cool!";
    }
}
loaderManager.init(0, new CursorLoader.Builder(getContentResolver(), MY_TABLE_URI)
    .projection(...)
    .selection(...)
    .sortOrder(...), ...);

me.tatarka.loadie:loadie-rx contains an RxLoader to easily accept an observable.

loaderManager.init(0, RxLoader.create(myObservable), ...);

Providing your own LoaderManager

LoaderManager isn't tied to any specific component. You can make your own by retaining it across configuration changes and calling the 4 lifecycle methods (start(), stop(), detach(), and destroy()). For example, here is a simple one using an activity's onRetainNonConfigurationInstance().

public class MainActivity extends Activity {

    LoaderManager loaderManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get a retained instance or create a new one.
        loaderManager = (LoaderManager) getLastNonConfigurationInstance();
        if (loaderManager == null) {
            loaderManager = new LoaderManager();
        }
        // We immediately have views, start delivering callbacks.
        loaderManager.start();
        setContentView(R.layout.activity_main);
        // we don't need to call stop() because the views are never detached. It would be necessary
        // in, ex a fragment where the views could be destroyed but the fragment is still around.
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            // Activity is done, cancel any loaders.
            loaderManager.destroy();
        } else {
            // Otherwise, just detach callbacks.
            loaderManager.detach();
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        return loaderManager;
    }
}

Testing Loaders

You can test loaders synchronously with LoaderTester in me.tatarka.loadie:loadie-test.

@Test
public void my_loader_test() {
    // Just wait for loader to complete.
    LoaderTester.runSynchronously(new MyLoader());
    // Get the first result.
    String result = LoaderTester.getResultSynchronously(new MyLoader());
    // Get all results.
    Iterator<String> results = LoaderTester.getResultsSynchronously(new MyLoader());
    String result1 = results.next();
    String result2 = results.next();
    String result3 = results.next();
}

loadie's People

Contributors

evant avatar

Stargazers

Pranav Lathigara avatar  avatar Ersin Ertan avatar 王亟亟 avatar mhelder avatar Xiaohai.lin avatar Jungle avatar Florent CHAMPIGNY avatar Dimitry avatar Wade avatar Dmitriy Voronin avatar Sean Amos avatar ligi avatar lyrachord avatar

Watchers

Thanh Le avatar  avatar James Cloos avatar  avatar

Forkers

naseemakhtar994

loadie's Issues

Conductors lifecycle listener for onLoaderResult and onRestoreViewState order annoyance

The problem/annoyance I have is for the situation where:

  • onCreateView() and myProfileLoader.start()
  • onLoaderResult() and populateViewWithLoaderResultExFirstName()
  • modify result value that is in the view firstName
  • rotate device and onSaveViewState()
  • onRestoreViewState()
  • onLoaderResult() overwrites modified data with loaders original data

As a quick fix I have a restoreViewState() after onLoaderResult(), which loads the cached results, then overwrites it with the Bundle savedViewState which is now kept local to the class.

Shouldn't the result be loaded prior to the view state restoration, thus keeping the most recent changes in the view?

public class MainCont extends Controller {

  Bundle savedViewState;
  //boolean overwriteEt = true;

  LoaderManager loaderManager;
  AsyncTaskLoader<String> asyncTaskLoader;
  Loader.Callbacks<String> loaderCallbacks = new Loader.Callbacks<String>() {

    @Override public void onLoaderStart() {
    }

    @Override public void onLoaderResult(String result) {
      //if (overwriteEt) et.setText(result);
      et.setText(result);
      restoreViewState();
    }

    @Override public void onLoaderError(Throwable error) {

    }

    @Override public void onLoaderSuccess() {

    }
  };

  private void restoreViewState() {
    if (savedViewState != null) {
      et.setText(savedViewState.getString("a"));
    }
  }

  EditText et;
  Button btn;

  public MainCont() {
    loaderManager = LoaderManagerProvider.forController(this);
    asyncTaskLoader = loaderManager.init(1, new Loader.Create<AsyncTaskLoader<String>>() {
      @Override public AsyncTaskLoader<String> create() {
        return new AsyncTaskLoader<String>() {
          @Override protected String doInBackground() {
            try {
              Thread.sleep(2000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            return "Do in back";
          }
        };
      }
    }, loaderCallbacks);
  }

  @NonNull @Override protected View onCreateView(@NonNull LayoutInflater layoutInflater,
      @NonNull ViewGroup viewGroup) {
    View root = layoutInflater.inflate(R.layout.cont_main, viewGroup, false);
    btn = (Button) root.findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //overwriteEt = false;
      }
    });
    et = (EditText) root.findViewById(R.id.et);
    if (!asyncTaskLoader.isRunning() && !asyncTaskLoader.isSuccess()) {
      asyncTaskLoader.start();
    }
    return root;
  }

  @Override protected void onAttach(@NonNull View view) {
    super.onAttach(view);
  }

  @Override protected void onDetach(@NonNull View view) {
    super.onDetach(view);
  }

  @Override protected void onSaveViewState(@NonNull View view, @NonNull Bundle outState) {
    outState.putString("a", et.getText().toString());
    super.onSaveViewState(view, outState);
  }

  @Override protected void onRestoreViewState(@NonNull View view, @NonNull Bundle savedViewState) {
    super.onRestoreViewState(view, savedViewState);
    this.savedViewState = savedViewState;
  }
}

Initialization location for rxloadie, conductor, retrofit

Say for a reset password screen, using conductor, rxjava1, retrofit, if you init the loader on reset button press, which then uses the editText text as the recovery email for retrofit. On rotation will not persist the response because the loader is unInit. However if your init in onCreateView, your retrofit call is init with empty text.

The given observable must be cold since it's not expected to run until @link #start() is called.

Does this imply that the retrofit observable is hot?
I made a few attempts but could not get the configuration correct.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.