{"id":19260692,"url":"https://github.com/evant/loadie","last_synced_at":"2025-04-21T16:32:09.996Z","repository":{"id":57736726,"uuid":"68436985","full_name":"evant/loadie","owner":"evant","description":"Android Loaders for the rest of us","archived":false,"fork":false,"pushed_at":"2020-06-14T22:49:41.000Z","size":135,"stargazers_count":14,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-01T14:38:18.913Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/evant.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-09-17T06:55:50.000Z","updated_at":"2018-09-18T05:24:02.000Z","dependencies_parsed_at":"2022-08-24T14:57:22.657Z","dependency_job_id":null,"html_url":"https://github.com/evant/loadie","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evant%2Floadie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evant%2Floadie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evant%2Floadie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evant%2Floadie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/evant","download_url":"https://codeload.github.com/evant/loadie/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250091025,"owners_count":21373303,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T19:22:32.575Z","updated_at":"2025-04-21T16:32:09.370Z","avatar_url":"https://github.com/evant.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"Loadie\n======\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/me.tatarka.loadie/loadie/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/me.tatarka.loadie/loadie)\n\nLoaders for the rest of us.\n\nThe concept of loaders in Android is pretty great: a way to do async work in a lifecycle-aware way.\nUnfortunately, the implementation is pretty bad. Loadie attempts to fix this in several ways:\n\n* Very simple loader interface for implementing a loader, only 3 possible methods to override.\nCompare that to Android loader's 6.\n* A clear separation between creating loaders and starting them.\n* Not tied into any component, you just need to call the 4 lifecycle methods on LoaderManager at the\ncorrect time, though default implementations for Activities and Fragments are provided.\n* Callback when the loader starts running so you can update your ui.\n* Explicit error handline with `onLoaderError()`.\n* Results are _always_ delivered async, so you don't have to guess when the callbacks are called vs your view setup logic.\n\n## Download\n\n```groovy\n// Base lib\ncompile 'me.tatarka.loadie:loadie:0.2'\n// LoaderMangerProvider for Activity and Fragment\ncompile 'me.tatarka.loadie:loadie-components:0.2'\n// LoaderManagerProvider for Conductor\ncompile 'me.tatarka.loadie:loadie-conductor:0.2'\n// AsyncTaskLoader and CursorLoader\ncompile 'me.tatarka.loadie:loadie-support:0.2'\n// RxLoader\ncompile 'me.tatarka.loadie:loadie-rx:0.2'\n// LoaderTester\nandroidTestCompile 'me.tatarka.loadie:loadie-test:0.2'\n```\n\n## Creating a Loader\n\nTo create a loader, you subclass `Loader` and implement `onStart()` and optionally `onCancel()` and\n`onDestroy()`.\n\n```java\npublic class MyLoader extends Loader\u003cString\u003e {\n    // Convenience creator for loaderManager.init()\n    public static final Create\u003cMyLoader\u003e CREATE = new Create\u003cMyLoader\u003e() {\n        @Override\n        public MyLoader create() {\n            return new MyLoader();\n        }\n    };\n\n    @Override\n    protected void onStart(Receiver receiver) {\n        // Note loader doesn't handle threading, you have to do that yourself.\n        api.doAsync(new ApiCallback() {\n            public void onResult(String result) {\n                // Make sure this happens on the main thread!\n                receiver.success(result);\n            }\n          \n            public void onError(Error error) {\n                receiver.error(error); \n            }\n        });\n    }\n\n    // Overriding this method is optional, but if you can cancel your call when it's no longer needed, you should.\n    @Override\n    protected void onCancel() {\n        api.cancel();\n    }\n\n    // Overriding this method is optional and allows you to clean up any resources.\n    @Override\n    protected void onDestroy() {\n\n    }\n}\n```\n\nIn your async operation you call `Receiver#result(value)` as many times as you have results and then\neither `Receiver#success()` or `Receiver#error(error)` exactly once to notify the work has ended or\nthere was an error. If you have used rxjava this contract should seem familer. There is also a\nconvenience `Receiver#success(value)` when you only have a single value to deliver.\n\nAs mentioned above, loaders don't to any threading for you. You are responsible for getting the work\noff the main thread and delivering the results back to the main thread.\n\n## Using a Loader\n\nIt most cases you will manage loaders through a `LoaderManager` that you obtain from a \n`LoaderManagerProvider`. This will manage the lifecycle for you, ensuring your callbacks happen when \nthey need to. For example, using `me.tatarka.loadie:loadie-components` and in an Activity, you would \ndo:\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        LoaderManager loaderManager = LoaderManagerProvider.forActivity(this);\n        // Creates a new loader or returns an existing one if it's already created.\n        final MyLoader myLoader = loaderManager.init(0, MyLoader.CREATE, new Loader.CallbacksAdapter\u003cString\u003e() {\n            @Override\n            public void onLoaderStart() {\n                // Update your ui to show you are loading something\n            }\n\n            @Override\n            public void onLoaderResult(String result) {\n                // Update your ui with the result\n            }\n            \n            @Override\n            public void onLoaderError(Throwable error) {\n                // Update your ui with the error\n            }\n\n            @Override\n            public void onLoaderComplete() {\n                // Optionally do something when the loader has completed\n            }\n        });\n        // The loader won't actually run until you call this!\n        myLoader.start();\n        \n        setContentView(R.layout.activity_main);\n        // view setup stuff...\n        \n        button.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View view) {\n                // The separation between initialization and starting, means it's easy to react to user events!\n                myLoader.restart();\n            }\n        });\n    }\n}\n```\n\n`me.tatarka.loadie:loadie-conductor` has a `LoaderManagerProvider` for [Conductor](https://github.com/bluelinelabs/Conductor)\nif that's your thing. It will ensure that the callbacks are not run when the view is not attached.\n\n```java\npublic class MyController extends Controller {\n\n    LoaderManager loaderManager;\n\n    public TestController() {\n        loaderManager = LoaderManagerProvider.forController(this);\n    }\n\n    @NonNull\n    @Override\n    protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {\n        return ...;\n    }\n}\n```\n\n## Built-in Loaders\n\nThere are a few built-in loaders for some common cases. `me.tatarka.loadie:loadie-support` has \nloaders that mirror the ones in the support lib.\n\n```java\npublic class MyAsyncTaskLoader extends AsyncTaskLoader\u003cString\u003e {\n    @Override\n    protected String doInBackground() {\n        // Do lots of work to get a string.\n        return \"Cool!\";\n    }\n}\n```\n\n```java\nloaderManager.init(0, new CursorLoader.Builder(getContentResolver(), MY_TABLE_URI)\n    .projection(...)\n    .selection(...)\n    .sortOrder(...), ...);\n```\n\n`me.tatarka.loadie:loadie-rx` contains an `RxLoader` to easily accept an observable.\n\n```java\nloaderManager.init(0, RxLoader.create(myObservable), ...);\n```\n\n## Providing your own LoaderManager\n\n`LoaderManager` isn't tied to any specific component. You can make your own by retaining it across\nconfiguration changes and calling the 4 lifecycle methods (`start()`, `stop()`, `detach()`, and \n`destroy()`). For example, here is a simple one using an activity's `onRetainNonConfigurationInstance()`.\n\n```java\npublic class MainActivity extends Activity {\n\n    LoaderManager loaderManager;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        // Get a retained instance or create a new one.\n        loaderManager = (LoaderManager) getLastNonConfigurationInstance();\n        if (loaderManager == null) {\n            loaderManager = new LoaderManager();\n        }\n        // We immediately have views, start delivering callbacks.\n        loaderManager.start();\n        setContentView(R.layout.activity_main);\n        // we don't need to call stop() because the views are never detached. It would be necessary\n        // in, ex a fragment where the views could be destroyed but the fragment is still around.\n    }\n\n    @Override\n    protected void onDestroy() {\n        super.onDestroy();\n        if (isFinishing()) {\n            // Activity is done, cancel any loaders.\n            loaderManager.destroy();\n        } else {\n            // Otherwise, just detach callbacks.\n            loaderManager.detach();\n        }\n    }\n\n    @Override\n    public Object onRetainNonConfigurationInstance() {\n        return loaderManager;\n    }\n}\n```\n\n## Testing Loaders\n\nYou can test loaders synchronously with `LoaderTester` in `me.tatarka.loadie:loadie-test`.\n\n```java\n@Test\npublic void my_loader_test() {\n    // Just wait for loader to complete.\n    LoaderTester.runSynchronously(new MyLoader());\n    // Get the first result.\n    String result = LoaderTester.getResultSynchronously(new MyLoader());\n    // Get all results.\n    Iterator\u003cString\u003e results = LoaderTester.getResultsSynchronously(new MyLoader());\n    String result1 = results.next();\n    String result2 = results.next();\n    String result3 = results.next();\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fevant%2Floadie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fevant%2Floadie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fevant%2Floadie/lists"}