{"id":13989275,"url":"https://github.com/passsy/CompositeAndroid","last_synced_at":"2025-07-22T10:31:46.737Z","repository":{"id":66131998,"uuid":"57997098","full_name":"passsy/CompositeAndroid","owner":"passsy","description":"Composition over inheritance for Android components like Activity or Fragment","archived":true,"fork":false,"pushed_at":"2019-03-10T20:17:08.000Z","size":1578,"stargazers_count":515,"open_issues_count":7,"forks_count":25,"subscribers_count":27,"default_branch":"master","last_synced_at":"2024-08-09T13:15:38.362Z","etag":null,"topics":["activitiy","android","composite","composition","delegation","fragment","inheritance"],"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/passsy.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-05-03T19:42:34.000Z","updated_at":"2024-07-09T11:52:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"945c6f94-c2db-4b3d-91cc-4cc664ef7858","html_url":"https://github.com/passsy/CompositeAndroid","commit_stats":null,"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/passsy%2FCompositeAndroid","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/passsy%2FCompositeAndroid/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/passsy%2FCompositeAndroid/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/passsy%2FCompositeAndroid/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/passsy","download_url":"https://codeload.github.com/passsy/CompositeAndroid/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227079157,"owners_count":17727974,"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":["activitiy","android","composite","composition","delegation","fragment","inheritance"],"created_at":"2024-08-09T13:01:35.333Z","updated_at":"2024-11-29T08:30:46.447Z","avatar_url":"https://github.com/passsy.png","language":"Java","readme":"# CompositeAndroid\n\n![License](https://img.shields.io/badge/license-Apache%202-green.svg?style=flat)\n\n*Composition over inheritance*\n\nAllows to add functionality into an Android `Activity`. Just because we all have a `BaseActivity` in our projects containing too much unused stuff. When it grows, it get unmaintainable.\n\n## Possible Usecases\n\n- Plugin for the GooglePlayApiClient handling all the edgecases\n- Wrap your layout in a predefined container by overriding `setContentView()`\n- a Plugin showing a loading spinner\n- a Plugin for requesting permissions and automatically handling all response codes\n- gradually add libraries like [Mosby](https://github.com/sockeqwe/mosby) (without extending from a `MvpActivity`) or [Flow](https://github.com/square/flow) to your Activities when you need it\n- and **so much more...**\n\n## State of the Art\n\nGiven you have an `Activity` showing a list of tweets (`TweetStreamActivity`) and you want add view tracking. \n\n### Inheritance \n\nYou could do it with inheritance and use `TrackedTweetStreamActivity` from now on:\n\n```java\npublic class TrackedTweetStreamActivity extends TweetStreamActivity {\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n        Analytics.trackView(\"stream\");\n    }\n}\n```\n\nmore likely you would create a `TrackedActivity` and extend the `TweetStreamActivity` from it:\n\n```java\npublic abstract class TrackedActivity extends AppCompatActivity {\n\n    public abstract String getTrackingName();\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n        Analytics.trackView(getTrackingName());\n    }\n}\n```\n\n```java\npublic class TrackedTweetStreamActivity extends TrackedActivity {\n\n    @Override\n    public String getTrackingName() {\n        return \"stream\";\n    }\n}\n```\n\nBoth solutions work but don't scale well. You'll most likely end up with big inheritance structures:\n\n```java\nclass MvpActivity extends AppCompatActivity { ... }\n\nclass BaseActivity extends AppCompatActivity { ... }\n\nclass BaseMvpActivity extends MvpActivity { ... }\n\nclass WizardUiActivity extends BaseActivity { ... }\n\nclass TrackedWizardUiActivity extends WizardUiActivity { ... }\n\nclass TrackedBaseActivity extends BaseActivity { ... }\n\nclass TrackedMvpBaseActivity extends BaseMvpActivity { ... }\n```\n\n### Delegation\n\nSome libraries out there provide both, a specialized `Activity` extending `AppCompatActivity` and a delegate with a documentation when to call which function of the delegate in your `Activity`.\n\n```java\npublic class TrackingDelegate {\n\n    /**\n     * usage:\n     * \u003cpre\u003e{@code\n     *\n     * @Override\n     * protected void onResume() {\n     *     super.onResume();\n     *     mTrackingDelegate.onResume();\n     * }\n     * } \u003c/pre\u003e\n     */\n    public void onResume() {\n        Analytics.trackView(\"\u003cviewName\u003e\");\n    }\n\n}\n```\n\n```java\npublic class TweetStreamActivity extends AppCompatActivity {\n\n    private final TrackingDelegate mTrackingDelegate = new TrackingDelegate();\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n        mTrackingDelegate.onResume();\n    }\n}\n```\n\nThis is an elegant solution but breaks when updating such a library and the delegate call position has changed. Or when the delegate added new callbacks which don't get automatically implemented by increasing the version number in the `build.gradle`.\n\n# Composite Android solution\n\nCompositeAndroid let's you add delegates to your Activity without adding calls to the correct location. Such delegates are called `Plugins`. A Plugin is able to inject code at every position in the Activity lifecycle. It is able to override every method.\n\n\n#### Get Started [![Download](https://api.bintray.com/packages/passsy/maven/CompositeActivity/images/download.svg) ](https://bintray.com/passsy/maven/CompositeActivity/_latestVersion)\n\nCompositeAndroid is available via [jcenter](http://blog.bintray.com/2015/02/09/android-studio-migration-from-maven-central-to-jcenter/)\n\n```gradle\ndependencies {\n    // it's very important to use the same version as the support library\n    def supportLibraryVersion = \"25.0.0\"\n    \n    // contains CompositeActivity\n    implementation \"com.pascalwelsch.compositeandroid:activity:$supportLibraryVersion\"\n\n    // contains CompositeFragment and CompositeDialogFragment\n    implementation \"com.pascalwelsch.compositeandroid:fragment:$supportLibraryVersion\"\n\n\n    // core module (not required, only abstract classes and utils)\n    implementation \"com.pascalwelsch.compositeandroid:core:$supportLibraryVersion\"\n}\n```\n\n#### Extend from a composite implementation\n\nExtend from one of the composite implementations when you want to add plugins. This is the only inheritance you have to make.\n\n```diff\n- public class MyActivity extends AppCompatActivity {\n+ public class MyActivity extends CompositeActivity {\n```\n\n```diff\n- public class MyFragment extends Fragment { // v4 support library\n+ public class MyFragment extends CompositeFragment {\n```\n\n\n#### Add a plugins\n\nUse the constructor to add plugins. Do not add plugins in `#onCreate()`. That's too late. Many `Activity` methods are called before `#onCreate()` which could be important for a plugin to work.\n\n```java\npublic class MainActivity extends CompositeActivity {\n\n    final LoadingIndicatorPlugin loadingPlugin = new LoadingIndicatorPlugin();\n\n    public MainActivity() {\n        addPlugin(new ViewTrackingPlugin(\"Main\"));\n        addPlugin(loadingPlugin);\n    }\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        // ...\n\n        // example usage of the LoadingIndicatorPlugin\n        loadingPlugin.showLoadingIndicator();\n    }\n}\n```\n\nRead more about the ordering of the Plugins [here](https://github.com/passsy/CompositeAndroid/wiki/Ordering-of-plugins-and-the-result-on-the-call-order)\n\n#### Write a plugin\n\n\nThis is the strength of CompositeAndroid. You don't really have to learn something new. It works like you'd extend you `Activity` to add functionality. Let's change the `TrackedActivity` from above and create a `ViewTrackingPlugin`.\n\nHere the original\n```java\npublic abstract class TrackedActivity extends AppCompatActivity {\n\n    public abstract String getTrackingName();\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n        Analytics.trackView(getTrackingName());\n    }\n}\n```\n\nAs plugin:\n```java\npublic class ViewTrackingPlugin extends ActivityPlugin {\n\n    private final String mViewName;\n\n    protected TrackedPlugin(final String viewName) {\n        mViewName = viewName;\n    }\n\n    @Override\n    public void onResume() {\n        super.onResume();\n        Analytics.trackView(mViewName);\n    }\n}\n```\n\nThe implementation inside of `onResume()` hasn't changed!\n\n### Plugin features\n\nHere some information about plugins. The Activity example is used but it works the same for other classes, too.\n\n- it's possible to override **every** Activity method from a `Plugin`\n- execute code before calling `super` executes code before `super` of Activity\n- explicitly not calling `super` is allowed and results in not calling super of the `Activity`. (The activity will tell if the `super` call was required)\n- execute code after calling `super` executes code after `super` of Activity\n\n### restrictions\n\nNot everything works exactly like you'd use inheritance. Here is a small list of minor things you have to know:\n\n#### Important for all Plugin authors\n- you can't call an `Activity` method of a `Plugin` such as `onResume()` or `getResources()`. Otherwise the call order of the added plugins is not guaranteed. Instead call those methods on the real `Activity` with `getActivity.onResume()` or `getActivity.getResources()`.\n\n#### onRetainNonConfigurationInstace\n- `CompositeActivity#onRetainCustomNonConfigurationInstance()` is final and required for internal usage, use `CompositeActivity#onRetainCompositeCustomNonConfigurationInstance()` instead\n- `CompositeActivity#getLastCustomNonConfigurationInstance()` is final and required for internal usage, use `CompositeActivity#getLastCompositeCustomNonConfigurationInstance()` instead\n- Saving a NonConfigurationInstance inside of a `Plugin` works by overriding `onRetainNonConfigurationInstance()` and returning an instance of `CompositeNonConfigurationInstance(key, object)`. Get the data again with `getLastNonConfigurationInstance(key)` and make sure you use the correct `key`.\n\n## Project stage\n\n`CompositeAndroid` gets used in productions without major problems. There could be more performance related improvements but it works reliably right now.\n\nMinor problems are:\n- Support lib updates **sometimes** require and update of `CompositeAndroid`. I didn't expect this because the API should be really stable, but it happened in the past (upgrading from `24.1.0` to `24.2.0`). That's why `CompositeAndroid` has the same version name as the support library. Yes, the support library can be used with and older `CompositeAndroid` version. But it can break, as it happened already. Then again all upgrades from `24.2.1` where 100% backwards compatible. We'll see what the future brings.\n- Generating a new release cannot be fully automated right now. It requires some steps in Android Studio to generate overrides and format the generated sources.\n- Some methods are edge cases like `getLastNonConfigurationInstance()` and `onRetainCustomNonConfigurationInstance()` did require manual written code.\n\nIt was a proof of conecpt and it turned out to work great. So great I haven't touched it a lot after the initial draft. Things like the documentation are still missing.\nI'm still keeping this project up to date but I don't invest much time in performance improvements. I don't need it, it works at it is for me.\n\n## Inspiration and other Android Composition Libraries\n\n- [Navi](https://github.com/trello/navi) of course, but\n    - it doesn't support all methods (only methods without return value)\n    - it does only support code execution before or after calling `super`, not very flexible\n    - no plugin API\n- [Lightcycle](https://github.com/soundcloud/lightcycle)\n    - supports only basic lifecycle methods.\n- [Decorator](https://github.com/eyeem/decorator)\n    - works only in scope of your own project. It doesn't allow including libraries providing plugins because the is no global Activity implementation.\n    - Every \"DecoratedActivity\" is generated for a specific usecase based on a blueprint you have to create every time\n\n# License\n\n```\nCopyright 2016 Pascal Welsch\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","funding_links":[],"categories":["Java"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpasssy%2FCompositeAndroid","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpasssy%2FCompositeAndroid","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpasssy%2FCompositeAndroid/lists"}